FileOutputStream Java


Two most frequently used classes from java.io package used for file copying are FileInputStream and FileOutputStream. FileInputStream java is used to read from a file and FileOutputStream Java is used to write into a file.
Following example uses both FileInputStream and FileOutputStream Java.
import java.io.*;
public class CopyFile
{
  public static void main(String args[]) throws IOException
  {
    FileInputStream fis = new FileInputStream("abc.txt");
    FileOutputStream fos = new FileOutputStream("def.txt");

    int temp;
    while((temp =  fis.read()) != -1)
    {
      fos.write(temp);
    }
    fos.close();
    fis.close();
  }
}

FileInputStream fis = new FileInputStream(“abc.txt”);
FileOutputStream fos = new FileOutputStream(“def.txt”);

abc.txt file is opened in read mode by FileInputStream class and def.txt file is opened in write mode by FileOutputStream Java class.

int temp;
while((temp = fis.read()) != -1)
{
fos.write(temp);
}

read() method reads byte by byte from the source file abc.txt, converts the byte into its ASCII integer value and returns. For example, A existing in abc.txt file is read and returned as 65. For this reason temp is taken as int data type. read() method comes with another property of returning -1 when EOF comes. That is, file reading ends when read() method returns -1.

The write() method of FileOutputStream Java takes the 65 ASCII integer value, converts back into original character A and writes into the destination file def.txt.

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

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

More explanation is available on the above code at File copying with byte streams

Leave a Comment

Your email address will not be published.