This is the concrete (which we can create an object or it contains all defined methods) sub- class of all InputStream class. This class is always used to open the file in read mode. Opening the file in read mode is nothing but creating an object of FileInputStream class.
FileInputStream (String fname) throws FileNotFoundException
For example:
FileInputStream fis=new FileInputStream ("abc.txt");
If the file name abc.txt does not exist then an object of FileInputStream fis is null and hence we get FileNotFoundException. If the file name abc.txt is existing then the file abc.txt will be opened successfully in read mode and an object fis will point to beginning of the file.
This is the concrete sub-class of all OutputStream classes. This class is always used for opening the file in write mode is nothing but creating an object of FileOutputStream class.
1. FileOutputStream (String fname); 2. FileOutputStream (String fname, boolean flag);
If the flag is true the data will be appended to the existing file else if flag is false the data will be overlapped with the existing file data.
If the file is opened in write mode then the object of FileOutputStream will point to that file which is opened in write mode. If the file is unable to open in write mode an object of FileOutputStream contains null.
Write the following JAVA programs: 1) create a file that should contain 1 to 10 numbers. 2) read the data from the file which is created above.
Answer:
1)
import java.io.*; class Fos { public static void main (String [] args) { try { String fname=args [0]; FileOutputStream fos=new FileOutputStream (fname, true);// mean append mode for (int i=1; i<=10; i++) { fos.write (i); } fos.close (); } catch (IOException ioe) { System.out.println (ioe); } catch (ArrayIndexOutOfBoundsException aiobe) { System.out.println ("PLEASE PASS THE FILE NAME..!"); } System.out.println ("DATA WRITTEN..!"); } };
2)
import java.io.*; class Fis { public static void main(String[] args) { try { String fname=args [0]; FileInputStream fis=new FileInputStream (fname); int i; while ((i=fis.read ())!=-1) { System.out.println (i); } fis.close (); } catch (FileNotFoundException fnfe) { System.out.println ("FILE DOES NOT EXIST..!"); } catch (IOException ioe) { System.out.println (ioe); } catch (ArrayIndexOutOfBoundsException aiobe) { System.out.println ("PLEASE PASS THE FILE NAME..!"); } } };