One machine can do the work of fifty ordinary men. No machine can do the work of one extraordinary man

Sunday, January 23, 2011

How to print the content of any text file?

Write a program to read lines from a text file and display the content to the user.

Hint:
         You may have to use FileInputStream, InputStreamReader and
         BufferedReader classes.
         When you ends the reading readLine() method will give you null values

         FileInputStream fs = new FileInputStream("tutorial.txt");
         BufferedReader in = new BufferedReader(new InputStreamReader(fs));


Answer :  "tutorial.txt" is my file name. you have to use a existing file name in your computer. if it is not in the same folder that you save this java programe, you have to give the full path of that file.


import java.io.*;


class File{
public static void main(String args[]) throws IOException { 
FileInputStream fs = new FileInputStream("tutorial.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(fs));
String text=in.readLine();


while(text!=null){
System.out.println(text);
text=in.readLine();
}
  }
}

3 comments:

  1. This is great macho... I'll try it tomorrow morning. I'm going to sleep now.

    ReplyDelete