在Java中读取.tsv文件

ta4*_*4le 6 java csv

我是初学者,我正在尝试用 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)

Ger*_*oni 7

首先,您应该移动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)

  • 我更新了答案,您现在可以看到如何打印字符串数组列表 (2认同)

Zab*_*uza 5

解释

  • 您必须在\t(选项卡)而不是\n(换行符)上进行拆分。因为你的lines 已经是单行,而不是多行。
  • 代码中的另一个问题是您手动关闭流,这是不安全的,并且会在异常情况下造成资源泄漏。您可以使用 try-with-resources 安全地关闭它。

蔚来

我可以建议一个更紧凑且可能更易读的版本,它使用 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)