Archive

Posts Tagged ‘Java-FileNotFoundException’

How to Read Text File in Java?

December 6th, 2008 No comments

Example below showing how to read text file

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 
/**
 * Example class for Reading text file
 *
 * @author Manet Yim (manet.yim at gmail dot com)
 */
public class ReadTextFile {
 
    public void readTextFile() {
 
        // Create new file object
        File file = new File("C:\Temp\TestFolder\TestFile.txt");
 
        try {
            // create file reader instance
            FileReader fr = new FileReader(file);
            // create memory buffer to store data read from file
            BufferedReader br = new BufferedReader(fr);
            // variable to store text from file
            String line = "";
            while ( (line = br.readLine()) != null ){
                System.out.println(line);
            }
            // close file reader
            fr.close();
            // close buffer reader
            br.close();
 
        }
        // it is required to catch exception in case file is not found
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // it is required to catch exception in case file cannot be read
        catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        ReadFile app = new ReadFile();
        app.readTextFile();
    }
 
}
Categories: Programming