Skip to content

Instantly share code, notes, and snippets.

@eleanor-em
Created September 26, 2019 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eleanor-em/d037a8195fe4bc4094c69fde3a661723 to your computer and use it in GitHub Desktop.
Save eleanor-em/d037a8195fe4bc4094c69fde3a661723 to your computer and use it in GitHub Desktop.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
class TooFewColumnsException extends Exception {
public TooFewColumnsException(int row) {
super("Error reading CSV file at row " + row + ": too few columns");
}
}
public class Csv {
public static void main(String[] args) {
try {
readCSV("test.csv");
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (TooFewColumnsException e) {
System.out.println(e.getMessage());
}
}
public static void readCSV(String filename)
throws FileNotFoundException, TooFewColumnsException {
try (Scanner scanner = new Scanner(new FileReader(filename))) {
String header = scanner.nextLine();
int columns = header.split(",").length;
int rowNum = 0;
while (scanner.hasNextLine()) {
++rowNum;
String row = scanner.nextLine();
if (row.split(",").length != columns) {
throw new TooFewColumnsException(rowNum);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment