Search code examples
javacsvopencsvcsvreader

Change delimiter in OpenCSV CSVReader


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!


Solution

  • 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);
            }
        }
    }