Java FileInputStream close() Example

FileInputStream class close() method example. This example shows you how to use close() method.


Syntax is : public void close() throws IOException
This method closes this file input stream and releases any system resources associated with the stream. If this stream has an associated channel then the channel is closed as well.

Here is the code.
/**
 * @(#) CloseFileInputStream.java
 * A class representing use of method close() of FileInputStream 
class in java.io Package.
 * @Version  07-June-2008
 @author   Rose India Team
 */
import java.io.*;

public class CloseFileInputStream {

    public static void main(String[] argsthrows IOException {

        try {
            //create file object.
            File file = new File("C://Mahendra.txt");
            
            byte[] b = new byte[]{'M','A','H','E','N','D','R','A','S','I','N'};
            FileOutputStream fOut = new FileOutputStream(file);
            fOut.write(b);
            System.out.print("Content of file : " );
            for(int i = 0;i<b.length; i++){
                System.out.print((char)b[i]);
            }                

            // Create object of FileInputStream class.
            FileInputStream fin = new FileInputStream(file);

            System.out.print("\nElements read : ");
            for (int i = 0; i < 8; i++) {
                System.out.print((charfin.read());
            }
            fin.close();
            System.out.print("\nclose method is called for this file stream.");
            System.out.println((charfin.read());
        }
        catch(Exception ex){
            System.out.println("\nCan't read more elements bacause file stream"
                    +" is closed now.");           
        }
    }
}

output of the program.
Content of file : MAHENDRASIN
Elements read : MAHENDRA
close method is called for this file stream.
Can't read more elements bacause file stream is closed now.

Post Comment
Name:
E-mail:
Contact no :
Comments:
  Refresh Image
Verify Image:
 
 
Your Comment's
 
 
 

HOME | COPYRIGHT | CONTACT US