Thursday, September 24, 2009

Java - open and read text file



/* 
 * To change this template, choose Tools | Templates 
 * and open the template in the editor. 
 */ 
 
package readfile;
 
import java.io.*;
 
 
public class Main {
 
    public static void main(String[] args) {
 
        // this assumes you have 'test.txt' in your working directory 
        String filename = "test.txt";
 
        try {
            // open file 
 
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            String line;
 
            // iterate through file's lines 
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
 
 
        }
 
        catch(Exception e) {
            System.out.println("file not found");
            System.out.println(e.getMessage());
            System.out.println(e.toString());
 
        }
 
 
    }
 
}
 
 
// output (for my test file): 
//  one 
//  two 
//  three 
 
 

No comments:

Post a Comment