我有两个给定的文件,其中每一行由四个元素组成,这些元素由','分隔。我想读入这两个文件,以便比较两者的行,但我也想列出它们。两个文件中的大多数行都是相同的,但两个文件中只有一行存在或者它们有一个不同的元素。我的元素类如下:
one
我还有一个CSVReader,我还没有完成,我想:
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()][]);
}
}
感谢您的帮助!
答案 0 :(得分:2)
将readCsv
类中的CSVReader
方法设为静态,以便您可以在任何地方调用它:
public static String[][] readCSV(String filename)
现在您可以致电CSVReader.readCsv
:
file1 = CSVReader.readCsv("./Root/files/file1.csv");
echo = CSVReader.readCsv("./Root/files/echo.csv");
答案 1 :(得分:0)
在这一行中
file1 = CSVReader("./Root/files/file1.csv"); /*cannot find symbol */
Java compiler&#34; seys&#34;你无法解决CSVReader
的问题
您的语法就像托盘一样调用函数。
一个解决方案就是这个代码snipet
CSVReader csvReader = new CSVReader();
file1 = csvReader.readCsv("./Root/files/file1.csv");
echo = csvReader.readCsv("./Root/files/echo.csv");
注意:csvReader
是一个变量。
另一种解决方案是将静态修饰符添加到readCsv
方法。在这种情况下,代码看起来像这样(没有构造函数调用)
file1 = CSVReader.readCsv("./Root/files/file1.csv");
echo = CSVReader.readCsv("./Root/files/echo.csv");