Created
September 26, 2019 01:54
-
-
Save eleanor-em/d037a8195fe4bc4094c69fde3a661723 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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