File Input Output Java

File input output operations involves IO streams like byte streams FileInputStream, FileOutputStream or character streams FileReader, FileWriter. This example is given on byte streams and later you can refer for character streams also.

Note: Before coming into programs it is advised to know byte streams vs character streams.

Example on File Input Output Java
import java.io.*;
public class FRDemo
{
  public static void main(String args[]) throws IOException
  {
    FileInputStream fis = new FileInputStream("wishes.txt");           // source file opened in read mode
    FileOutputStream fos = new FileOutputStream("greetings.txt");      // destination file opened in write mode

    int temp;
    while((temp = fis.read()) != -1)
    {
      fos.write(temp);                     // writes to file greetings.txt
      System.out.print((char)temp);        // writes at command prompt
    }

    fos.close();
    fis.close();
  }
}

File Input Output JavaOutput Screenshot on File Input Output Java

import java.io.*;

All the file input output operations in Java requires I/O stream classes from java.io package. The classes of this package used in the above program are FileInputStream, FileOutputStream and IOException.

FileInputStream fis = new FileInputStream(“wishes.txt”); // source file opened in read mode
FileOutputStream fos = new FileOutputStream(“greetings.txt”); // destination file opened in write mode

The FileInputStream constructor opens the source file wishes.txt in read mode and FileOutputStream constructor opens the destination file greetings.txt in write mode.

int temp;
while((temp = fis.read()) != -1)
{
fos.write(k); // writes to file greetings.txt
System.out.println((char)temp); // wries at command prompt
}

An integer temp is taken to store data temporarily while loop is going on. The read() method of FileInputStream reads byte by byte from wishes.txt, converts the byte into integer and returns. The retunred integer value is assigned to temp variable. The read() method has one more proeprty of returning -1 when EOF (End Of File) comes.

Inside the loop, the temp variable is passed to write() method of FileOutputStream. This write() method takes temp value, converts back to original char and writes into the destination file greetings.txt.

The loop continues until EOF is read by read() method. When EOF is read, -1 is returned and loop terminates.

fos.close();
fis.close();

When the job is over, close the streams so that memory is freed.

For more indepth explanation on this same file copying read File Copy Tutorial Java

Leave a Comment

Your email address will not be published.