readbyte from files
readbyte from files

File Handling in java programming:

 

File handling in java or in any programming language is a very  important concept. In java
File handling in java is done by input and output stream these Input and Output stream is contained in The java.io package. In java all files are in byte and java gives you power to read and write files in bytes or in character format.

In java file handling we have many method to read from a file or to write in the file by console these methods are contained in FileInputStream and FileOutputStream classes.

To read from a particular file , we can use a method read() that is defind with in FileInputStream and To write a file we use write() method defind in FileOutputStream.

 

Before we start file handling in java coding:

Please check these condition
1) Is Jdk(java development kit) is installed in your pc? If no then please click here to learn how to install jdk.
2) set PATH variable from control panel .Click here to see tutorial

To set path of java. By going to
CONTROL PANEL>SYSTEM>Advance system setting> Environment Variable> New
Then Variable Name: PATH
Variable Value: c:program filejavabin.
Then Ok
Variable value is your full path of java folder where it is installed.

3)To learn How to make java first program click here.

Ok now we can start coding and compiling the file handling in java program:

1)open Notepad
And write following code to read from file.

Codes:
import java.io.*;
class readFile
{
     public static void main(String args[]){
         int c;
         File f=new File(“buffer.txt”);
         FileReader fr= null;
        try{
             fr= new File Reader(f);
             System.out.println(“Reading from file”);
             while((c=fr.read())!=-1){
                   System.out.println((char) c);
                                                 }
            }
        catch(IOException ex){
             System.out.println(“following error is occupied”+ex);
                                           }
        finally{
            try {
                 fr.close();
             }
           catch(IOException e){
                  System.out.println(“error”);
             }
}

  }
}

 

File Handling in java programming
File Handling in java programming

Explanation of code:
1) java.io package is import because we use read() method and File Reader.
2)File f= New File() is use to create instance of input file Buffer.txt.
3)FileReader use to read from file by using read function by creating instance of File Reader .

Thanks for Reading post and please wait for next post in which we discribe how to write on file.

Register here to ask any query or visit contact us.

NO COMMENTS