Read line with Scanner

This code reads the file line by line. public static void readFileByLine(String fileName) { try { File file = new File(fileName); Scanner scanner = new Scanner(file); while (scanner.hasNext()) { System.out.println(scanner.next()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } You can also set a delimiter as a line separator and then perform the same. …

Read more

How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner

As per the javadoc for Scanner: When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method. That means that if the next token is not an int, it throws the InputMismatchException, but the token stays there. …

Read more

How to read a text file directly from Internet using Java?

Use an URL instead of File for any access that is not on your local computer. URL url = new URL(“http://www.puzzlers.org/pub/wordlists/pocket.txt”); Scanner s = new Scanner(url.openStream()); Actually, URL is even more generally useful, also for local access (use a file: URL), jar files, and about everything that one can retrieve somehow. The way above interprets …

Read more

Read CSV with Scanner()

Please stop writing faulty CSV parsers! I’ve seen hundreds of CSV parsers and so called tutorials for them online. Nearly every one of them gets it wrong! This wouldn’t be such a bad thing as it doesn’t affect me but people who try to write CSV readers and get it wrong tend to write CSV …

Read more

Scanner is skipping nextLine() after using next() or nextFoo()?

That’s because the Scanner.nextInt method does not read the newline character in your input created by hitting “Enter,” and so the call to Scanner.nextLine returns after reading that newline. You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself). Workaround: Either put a Scanner.nextLine call after …

Read more