我是初学者,我正在尝试用 Java 读取 .tsv 数据并将行保存到 ArrayList 中。我为它编写了一个方法,但我得到的唯一的东西就是行 ID,仅此而已......我找不到错误。请你帮助我好吗?
public static ArrayList<String[]> tsvr(File test2) throws IOException {
BufferedReader TSVReader = new BufferedReader(new FileReader(test2));
String line = TSVReader.readLine();
ArrayList<String[]> Data = new ArrayList<>(); //initializing a new ArrayList out of String[]'s
try {
while (line != null) {
String[] lineItems = line.split("\n"); //splitting the line and adding its items in String[]
Data.add(lineItems); //adding the splitted line array to the ArrayList
line = TSVReader.readLine();
} TSVReader.close();
} catch (Exception e) {
System.out.println("Something went wrong");
}
return Data;
}
Run Code Online (Sandbox Code Playgroud)
首先,您应该移动readLine一段时间,以便可以读取文件的所有行。然后你应该按制表符分割行,\t因为它是一个制表符分隔的文件
public static ArrayList<String[]> tsvr(File test2) {
ArrayList<String[]> Data = new ArrayList<>(); //initializing a new ArrayList out of String[]'s
try (BufferedReader TSVReader = new BufferedReader(new FileReader(test2))) {
String line = null;
while ((line = TSVReader.readLine()) != null) {
String[] lineItems = line.split("\t"); //splitting the line and adding its items in String[]
Data.add(lineItems); //adding the splitted line array to the ArrayList
}
} catch (Exception e) {
System.out.println("Something went wrong");
}
return Data;
}
Run Code Online (Sandbox Code Playgroud)
如果你想打印数组列表:
Data.forEach(array -> System.out.println(Arrays.toString(array)));
Run Code Online (Sandbox Code Playgroud)
\t(选项卡)而不是\n(换行符)上进行拆分。因为你的lines 已经是单行,而不是多行。我可以建议一个更紧凑且可能更易读的版本,它使用 NIO (Java 8 或更高版本),而不是修复其他答案已经做过的现有代码,它具有相同的功能:
return Files.lines(file.toPath())
.map(line -> line.split("\t"))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
如果你可以现代化你的方法参数,我建议用它Path path来代替File file,那么你可以简单地做Files.lines(path)
| 归档时间: |
|
| 查看次数: |
9233 次 |
| 最近记录: |