User Program Communication

Read from Text File in Java

Used to read a text file.


Syntax
import java.io*;

//create a FileReader object using the file name and path, the file reader reads the file by byte
FileReader file = new FileReader(fileNamePath); 

//feed the FileReader into a BufferedReader to read line by line
BufferedReader br = new BufferedReader(file);

//read a line from the BufferedReader
String fileLine = br.readLine();

file.close();
br.close();

Notes

Reader objects should always be closed to prevent a memory leak.

The BufferedReader reads a single line. On each additional call of the readLine() method, the BufferedReader advances to the next line of the file.

While a BufferedReader is most commonly used, other readers and scanners may be more suitable depending on the scenario. For example, when reading text files word by word, the Scanner class can be used.

This code should be wrapped in a try-catch block which checks for valid text format (IOException) and existence of the file (FileNotFoundException).


Example
import java.io*;

try {
    FileReader file = new FileReader(names.txt); 
    //feed the FileReader into a BufferedReader to read line by line
    BufferedReader br = new BufferedReader(file);

    String name = null; //
    //reads file until there are no more lines, using a null check
    while( (name = br.readLine()) ){
        System.out.println("Name: " + name);
    }
    file.close();
    br.close();
}
catch (IOException e) {
    System.out.println("The file is not a valid format for the reader!");
}
catch (FileNotFoundException f) {
    System.out.println("The file could not be found!");
}
    

< Commenting   |   Write to File >

© 2018 SyntaxDB. All Rights Reserved.