gpt4 book ai didi

java - 读入文件并比较每个元素

转载 作者:行者123 更新时间:2023-11-30 02:11:52 25 4
gpt4 key购买 nike

我有两个给定的文件,其中每行由四个元素组成,元素之间用“,”分隔。我想读入这两个文件以便比较两个文件的行,但我也想列出它们。两个文件中的大多数行都是相同的,但也有一些行仅出现在两个文件之一中,或者它们有一个元素不同。我的元素类如下:

public class Student {
public String name;
public Student (String name) {
this.name = name;
}
public static String[] toString(String name)
{
String s1 = ""; String s2 = ""; String s3 = ""; String s4 = "";
int position = 0;
for(int i = 0; name.charAt(i) != name.length(); i++)
{
if (name.charAt(i) == ',') {++position; continue;}
if (position == 0) s1 += name.charAt(i);
if (position == 1) s2 += name.charAt(i);
if (position == 2) s3 += name.charAt(i);
if (position == 3) s4 += name.charAt(i);
}
String[] s = new String[4];
return s;
}
}

我还有一个 CSVReader,我还没有完成,我想:

public class CSVReader {

/**
* This method reads in a *.csv file and saves every entry as elements
* from a twodimensional array.
*
* @param filename track to the file Pfad zur Datei, example
* ".Root/test/echo.csv"
* @return {@code String[][] s} where {@code s[i][j]}
* is the j-th value in the i-th line
*/
public String[][] readCSV(String filename) {
ArrayList<String[]> result = new ArrayList<>();

BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
StringBuilder stringBuilder = new StringBuilder();

try {
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
result.add(line.split(cvsSplitBy));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result.toArray(new String[result.size()][]);
}
}

我的问题是如何在主类中使用 CSVReader:

public class Main {

public static void main(String[] args) {

/**
* Read in "./Root/files/echo.csv" und "./Root/files/file1.csv"
* and output the correspondent warning on System.out
*/
String file1 = new String("");
String echo = "";
file1 = CSVReader("./Root/files/file1.csv"); /*cannot find
symbol */
echo = CSVReader("./Root/files/echo.csv"); // same error
}
}

感谢您的帮助!

最佳答案

CSVReader 类中的 readCsv 方法设为静态,以便您可以在任何地方调用它:

public static String[][] readCSV(String filename)

现在您可以调用CSVReader.readCsv:

file1 = CSVReader.readCsv("./Root/files/file1.csv");
echo = CSVReader.readCsv("./Root/files/echo.csv");

关于java - 读入文件并比较每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49824021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com