Posts

Showing posts with the label Read File

How to read a file in Java with BufferedReader?

Image
In this section, we will show you how to use java.io.BufferedReader to read content from a file. 1. Files.newBufferedReader (Java 8) In Java 8, there is a new method  Files.newBufferedReader(Paths.get("file"))  to return a  BufferedReader myFile.txt Main.java import java.io.BufferedReader ; import java.io.IOException ; import java.nio.file.Files ; import java.nio.file.Paths ; public class Main { public static void main ( String [] args) { StringBuilder stringBuilder = new StringBuilder(); try ( BufferedReader bufferedReader = Files . newBufferedReader ( Paths . get ( "C: \\ Users \\ 91807 \\ Desktop \\ myFile.txt" ))) { // read line by line String line ; while (( line = bufferedReader .readLine()) != null ) { stringBuilder .append( line ).append( " \n " ); } } catch ( IOException e) { System . err .format( "IOException: %s%n" , ...