Last active
October 30, 2015 10:16
-
-
Save antoni/00700918d236dd02377b to your computer and use it in GitHub Desktop.
Different ways of reading file line by line in Java (Java 8 on the bottom)
This file contains hidden or 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.BufferedReader; | |
| import java.io.File; | |
| import java.io.FileNotFoundException; | |
| import java.io.FileReader; | |
| import java.io.IOException; | |
| import java.nio.charset.Charset; | |
| import java.nio.file.Files; | |
| import java.nio.file.Path; | |
| import java.nio.file.Paths; | |
| import java.util.Scanner; | |
| import java.util.stream.Stream; | |
| public class FileLineReader { | |
| public static void readTextUsingScanner(String filepath) | |
| throws FileNotFoundException { | |
| Scanner scan = new Scanner(new File(filepath)); | |
| while (scan.hasNextLine()) { | |
| String line = scan.nextLine(); | |
| // process the line | |
| } | |
| } | |
| public static void readTextUsingBufferedReader1(String filepath) | |
| throws IOException, FileNotFoundException { | |
| try (BufferedReader br = new BufferedReader(new FileReader(new File( | |
| filepath)))) { | |
| String line; | |
| while ((line = br.readLine()) != null) { | |
| // process the line | |
| } | |
| } | |
| } | |
| /* Same as before but avoiding scope of 'line' leaking */ | |
| public static void readTextUsingBufferedReader(String filepath) | |
| throws IOException, FileNotFoundException { | |
| try (BufferedReader br = new BufferedReader(new FileReader(new File( | |
| filepath)))) { | |
| for (String line; (line = br.readLine()) != null;) { | |
| // process the line | |
| } | |
| // line is not visible here | |
| } | |
| } | |
| /* Java 8 */ | |
| public static void readTextJava8Style(String filepath) throws IOException, | |
| FileNotFoundException { | |
| try (BufferedReader reader = new BufferedReader(new FileReader( | |
| new File(filepath)))) { | |
| reader.lines().forEach(line -> { | |
| // process the line | |
| }); | |
| } | |
| } | |
| /* Java 8 */ | |
| public static void readTextJava8Style2(String filepath) throws IOException, | |
| FileNotFoundException { | |
| Path path = Paths.get(filepath); | |
| try (Stream<String> lines = Files.lines(path, Charset.defaultCharset())) { | |
| lines.forEachOrdered(line -> { | |
| // process the line | |
| }); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment