GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Saturday, December 18, 2010

Java IO - Reading A Text File

Reading one line from text file:

import java.io.*;

public class Main{

    public static void main(String[] args){
        try{
            File file = new File("D://data.txt");
            FileReader reader = new FileReader(file);
                                //FileNotFoundException
            BufferedReader textReader = new
                                        BufferedReader(reader);
            String text = textReader.readLine(); // IOException
            System.out.println(text);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }   
}



To Read A whole text, use:

import java.io.*;

public class Main{

    public static void main(String[] args){
        try{
            File file = new File("D://data.txt");
            FileReader reader = new FileReader(file);
            BufferedReader bReader = new BufferedReader(reader);

            String text = "";
            while(text!=null){
                text = bReader.readLine();
                System.out.println(text);
            }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
}




Share/Bookmark

No comments:

Post a Comment