Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

Copy Binary File

Problem : How you can make copy of a binary file?

Solution :
java.io.FileInputStream  will be used to read data from source binary file and java.io.FileOutStream will be used to write data to target binary file.

Program :

Step 1 - Coding

Create a text file c:/sunilos/CopyBinary.java and copy below contents.

import java.io.FileInputStream;
import java.io.FileOutputStream;

 * A program to copy a binary file to another file.
public class CopyBinary {

    public static void main(String[] args) throws Exception {
        String source = "c:/sunilos/sunilos1.jpg";
        String target = "c:/sunilos/sunilos.jpg";
        FileInputStream reader = new FileInputStream(source);
        FileOutputStream writer = new FileOutputStream(target);
        int ch = reader.read();
        while(ch!= -1){
            ch = reader.read();
        System.out.println(source + " is copied " + target);


Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy CopyBinary.java into 'c:\sunilos' folder.
  3. It is assumed that your hard drive has c:/sunilos/sunilos1.jpg file.
  4. Open your command prompt and go to  'c:\sunilos'
  5. Compile CopyBinary.java with help of 
    • javac CopyBinary.java command. Command will create CopyBinary.class file in the same folder.
  6. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java CopyBinary command.
  3. Now check your data open
    • c:/sunilos/sunilos.jpg


C:\sunilos>java -cp . com.sunilos.io.CopyBinary
c:/sunilos/sunilos1.jpg is copied c:/sunilos/sunilos.jpg


What is FileInputStream?

  • FileInputStream obtains input bytes from a file in a file system.
  • FileInputStream is meant for reading streams of raw bytes such as image data.

What is FileOutputStream?

  • A file output stream is an output stream for writing data to a File . Whether or not a file is available or may be created depends upon the underlying platform.
  • FileOutputStream is meant for writing streams of raw bytes such as image data.
Prachi Pacharne,
Oct 16, 2015, 7:21 AM
Prachi Pacharne,
Oct 16, 2015, 7:17 AM