javascript
Brief description  about Online courses   join in Online courses
OR

Reading and Writing to a file

Nirupama  Pathak
Nirupama Pathak
Java Developer

We can create constructors using FileInputStream to read a file. There are 2 types of Contructors we can use, lets have a look at them:

1.
InputStream f = new FileInputStream("D:/Project Modules/Hello.txt");

The above constructor takes a file name as a string to create an input stream object to read the file.


2.
File f = new File("D:/Project Modules/Hello.txt");
    InputStream f = new FileInputStream(f);


Now we have an object
"f" which can be used with several methods to read a stream or to do other operations on stream.

1. public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.

2. protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.

3. public int read(int r)throws IOException{}

This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's end of file.

4. public int read(byte[] r) throws IOException{}

This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If end of file -1 will be returned.

5. public int available() throws IOException{}

Gives the number of bytes that can be read from this file input stream. Returns an int.

Inputstreams are not good if we are reading characters from a file but it is useful if we have to read an image from a file.


The best way to read an input from a file is by using "
Scanner". Scanner is a class which is defined in java.util package which has several methods to read and process the data we read.

General Syntax of Scanner is:


Scanner Variable_Name = new Scanner ("File_Name");


The below program demonstrates the usage of Scanner to read from a file:


import java.io.*;
import java.util.*;

class FileInput {
    public static void main( String[ ] args) {
        File InputFile = new File("Hello.txt");  //File is part of java.io package, contents of Hello.txt is stored in InputFile variable

        try {
            Scanner input = new Scanner(InputFile); //contents of InputFile is scanned into input variable
            while(input.hasNext( )) {   //checks for the availability of next line, this method is part of Scanner class
                String inputline = input.nextLine( );  //stores the next line in inputline variable
                System.out.println(inputline);
              }
        }

        catch(FileNotFoundException e)  {
             System.err.format ("File Does Not Exist");
        }
    }
}

We can write anything we want to a file anywhere in our system using FileWriter class which is part of java.io package.

import java.io.*;

class FileOutput  {
    public static void main(String args[])  {
        try  {
            FileWriter FileOut = new FileWriter("OutPutFile.txt");  //FileOut object is created of type FileWriter
            BufferedWriter Output = new BufferedWriter(FileOut); //BufferedWriter is created to write to OutPutFile.txt
            Output.write("Silicon India Certified Java Developer Course");
            Output.close( );  //close the output stream
        }
        catch (Exception e)  {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

The above program writes the line "Silicon India Certified Java Developer Course" to OutPutFile.txt (also creates the file) in Project Modules folder.

Write your comment now