Java IO library provides various methods to read text files. I am going to demonstrate different ways you can do that.
Using FileReader:
It’s a very basic technique which assumes the correct character encoding. It reads file character by character. Obviously, bit inefficient.
String fileName = "file.txt"; try (FileReader fr = new FileReader(fileName)) { char ch; while ((ch = fr.read()) != -1) { System.out.print(ch); } } catch (Exception e) { e.printStackTrace(); }
Using FileReader with BufferedReader:
This is a better way than the previous one as it uses a buffer to read file per line instead of per character. This approach holds good when you know your file data is organized line by line, like a csv file. It gives you option to perform operations after reading every line, so that you don’t wait up until reading whole file.
String fileName = "file.txt"; try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); }
Using Scanner
String fileName = "file.txt"; try (Scanner scanner = new Scanner(new File(fileName))) { while (scanner.hasNext()){ System.out.println(scanner.nextLine()); } } catch (Exception e) { e.printStackTrace(); }
Using streams
In java 8, you can read files line by line with streams. Like below:
String fileName = "file.txt"; try (Stream<String> stream = Files.lines(Paths.get(fileName))) { stream.forEach(System.out::println); } catch (Exception e) { e.printStackTrace(); }
Streams with filter
Streams also give you option to filter lines based on certain conditions
String fileName = "file.txt"; List<String> list = null; try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) { String lines = br.lines().collect(Collectors.joining(System.lineSeparator())); list = stream.filter(line -> line.startsWith("Name:")).collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); }
Streams with BufferedReader
String fileName = "file.txt"; try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) { String lines = br.lines().collect(Collectors.joining(System.lineSeparator())) } catch (IOException e) { e.printStackTrace(); }