Pages

Program to read data from a file using FileInputStream class

/* Program to read data from a file using FileInputStream class */
import java.io.*;
class FileRead
{
  public static void main(String args[]) throws Exception
  {
    FileInputStream fis = new FileInputStream(“file1.txt”);
    /*  Read the size of the file */
    int size = fis.available(); /* available() returns no. of bytes in file1.txt */
    byte b [] = new byte[size]; /* create a byte array of file size */
   fis.read(b);
    String data = new String(b);  /* convert the byte array to string */
    System.out.println(“The contents of file1.txt are :  “ + data);
 }// end of main
}// end of class


/* The following program is used to read data from any file */
import java.io.*;
class FileRead2
{
  public static void main(String args[])throws Exception
  {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String ch=”yes”;
    while(ch.equals(“yes”))
    {
      System.out.println(“Enter the file name to Read  “);
      String fname = br.readLine();
        FileInputStream fis = new FileInputStream(fname);
        int size = fis.available(); /* available() returns no. of bytes in file1.txt */
        byte b [] = new byte[size]; /* create a byte array of file size */
        fis.read(b);
        String data = new String(b);  /* convert the byte array to string */
        System.out.println(“The contents of file1.txt are :  “ + data);
        fis.close();
        System.out.println(“Want to Continue(type yes/no) “);
        ch = br.readLine();
     } // end while
    } // end main       

  } // end class