CSVReader { public void read(BufferedReader reader, TableReader lineConsumer) { try { String line = reader.readLine(); if (line == null) { return; } ImmutableList<String> header = Arrays.stream(line.split(COLUMN_DELIMITER, -1)) .collect(ImmutableList.toImmutableList()); int headerLength = header.size(); lineConsumer.consumeHeader(header); line = reader.readLine(); while (line != null) { if (!line.isEmpty()) { String[] splitLine = line.split(COLUMN_DELIMITER, -1); Preconditions.checkState(splitLine.length == headerLength, String.format("Line incompatible with header.%n Line: %s%n Header: %s", Arrays.toString(splitLine), header)); ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (int i = 0; i < headerLength; i++) { builder.put(header.get(i), splitLine[i]); } lineConsumer.consumeLine(builder.build()); } line = reader.readLine(); } lineConsumer.fileFinished(); reader.close(); } catch (IOException e) { logger.error("Failed to read file", e); } }  void read(BufferedReader reader, TableReader lineConsumer); void read(File file, TableReader lineConsumer); static final String COLUMN_DELIMITER; }
@Test void testReadCSVFile() { SimpleTableReader consumer = new SimpleTableReader(); CSVReader reader = new CSVReader(); File testFile = new File("src/test/test.csv"); reader.read(testFile, consumer); ImmutableMap<String, String> line0 = ImmutableMap.<String, String>builder() .put("THIS", "1") .put("IS", "2") .put("A", "3") .put("TEST", "4") .build(); ImmutableMap<String, String> line1 = ImmutableMap.<String, String>builder() .put("THIS", "5") .put("IS", "6") .put("A", "7") .put("TEST", "8") .build(); Assertions.assertEquals(line0, consumer.getRow(0)); Assertions.assertEquals(line1, consumer.getRow(1)); }
@Test void testFileFinishedIsCalled() { TestTableReader tableReader = new TestTableReader(); new CSVReader().read(new File("src/test/test.csv"), tableReader); Assertions.assertTrue(tableReader.hasFileFinishedBeenCalled()); }