Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

File Read

Problem : How you can read charter by charter data from a text file and display on  Console?

Solution :
java.io.FileReader class has a read() method to read charters from a text file.

Program :

Step 1 - Coding

Create a text file c:/sunilos/FileRead.java  and copy below contents.

import java.io.FileReader;

/**
 * A program that reads data from a text file and print on Console.
 */
public class FileRead {

    public static void main(String[] args) throws Exception {
                //FileReader reads streams of characters
        FileReader reader = new FileReader("c:/sunilos/sunilos.txt");
       
        int ch = reader.read(); //Returns character's uni-code or -1 at End Of File
        char chr;
        while(ch!=-1){//Checks if EOF reached 
            chr =(char)ch;
            System.out.print( chr);
            ch = reader.read();
        }
    }

}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy FileRead.java  into 'c:\sunilos' folder.
  3. It is assumed that your hard drive has c:/sunilos/sunilos.txt file.
  4. Open your command prompt and go to  'c:\sunilos'
  5. Compile FileRead.java with help of 
    • javac FileRead.java command.  Command will create FileRead .class file in the same folder.
  6. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of
    • java FileRead command.

Output

Welcome in SunilOS Tutorial
Cheers,
SunilOS Technologies

FAQ

What is FileReader?

  • FileReader is meant for reading streams of characters.

Most Interesting methods in FileReader?

  • close() - Close the stream.
  • getEncoding() - Return the name of the character encoding being used by this stream.
  • read() - Read a single character.
  • read(char[] cbuf, int offset, int length) : Read characters into a portion of an array.
  • ready() - Tell whether this stream is ready to be read.

<<Previous | Next>>
ċ
FileRead.java
(1k)
Mahima Hardia,
Aug 19, 2011, 10:22 PM
Comments