by Dinesh Thakur

In this Java Example in the main () method of the class FileIOStream, an instance fileOutput of FileOutputStream is created to write to the file mydata.dat. Then using the for loop, we write the square of the value stored in the index variable i using the write () method to the file mydata.dat. The output stream is then closed by calling the close () method.

In order to read bytes from the file mydata.dat, we create an instance filelnput of the FilelnputStream class. We then read the bytes from the mydata.dat file one by one and display it on the screen. For this, we use the while loop in which the expression

(ch = filelnput.read())!= -1

reads a byte from the input stream, assigns it to the variable ch and checks whether it is -1 or not. If it is not equal to -1 then the byte is displayed on the screen. If ch = -1 then it indicates that end of file (EOF) is reached and the loop terminates. Finally, the program closes the input stream and terminates.

import java.io.*;

class FileIOStream
{
          public static void main(String[] args)
      {
             int ch; 
             try
            { 
                 //Create an instance of the output statream
                 FileOutputStream fileOutput = new FileOutputStream("mydata.dat");
                 //write data to the stream
                for(int i=1;i<=10;i++)
                    fileOutput.write(i);
                    fileOutput.close(); //close the output stream
            }
            catch(IOException e)   { e.printStackTrace(); }
            try
           {
                //Create an instance of the input stream
                FileInputStream fileInput=new FileInputStream("mydata.dat");
                //reading data from a file, unil Eof is reached
                while((ch=fileInput.read())!= -1)
                System.out.print(ch + " ");
                fileInput.close(); //close the input stream
           }
           catch(IOException e)  { e.printStackTrace(); }
      }
}

Write byte array to a file using FileOutputStream