1

I have the following piece of code which reads a CSV file.

public class TestMain {
    public static void parseTsv(String filePath) throws Exception {
        try (CSVReader reader = new CSVReader(new InputStreamReader(Objects.requireNonNull(TestMain.class.getResourceAsStream(filePath))))) {
            String[] line;
            while ((line = reader.readNext()) != null) {
                System.out.println(line[0] + " " + line[1]);
            }
        }
    }

    public static void main(String[] args) {
        try {
            parseTsv("path-to-tsv-file");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

And I want to modify the delimiter so that it can read tsv files (tab-separated). Any help would be greatly appreciated!

Stratos K
  • 341
  • 2
  • 14
  • 2
    Example [right here](https://opencsv.sourceforge.net/apidocs/com/opencsv/CSVParserBuilder.html) – g00se Feb 17 '23 at 11:27

1 Answers1

1

With g00se's help, please see below the correct code:

public class TestMain {
    public static void parseTsv(String filePath) throws Exception {
        try (CSVReader reader = new CSVReaderBuilder(new InputStreamReader(Objects.requireNonNull(TestMain.class.getResourceAsStream(filePath))))
                .withCSVParser(new CSVParserBuilder().withSeparator('\t').build())
                .build()) {
            String[] line;
            while ((line = reader.readNext()) != null) {
                System.out.println(line[0] + " " + line[1]);
            }
        }
    }

    public static void main(String[] args) {
        try {
            parseTsv("path-to-tsv-file");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
Stratos K
  • 341
  • 2
  • 14