io
Copy binary file with streams
With this example we are going to demonstrate how to copy a binary file using the FileInputStream and the FileOutputStream. In short, to copy a binary file with streams you should:
- Create a new FileInputStream, by opening a connection to an actual file, the file named by the path source name in the file system.
- Create a new FileOutputStream to write to the file with the specified target name.
- Use
read(byte[] b)API method of FileInputStream to read up to b.length bytes of data from this input stream into an array of bytes. - Use
write(byte[] b, int off, int len)API method of FileOutputStream to write len bytes from the specified byte array starting at offset off to this file output stream.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBinaryFileWithStreams {
public static void main(String[] args) {
String sourceFile = "input.dat";
String destFile = "output.dat";
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(sourceFile);
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int noOfBytes = 0;
System.out.println("Copying file using streams");
// read bytes from source file and write to destination file
while ((noOfBytes = fis.read(buffer)) != -1) {
fos.write(buffer, 0, noOfBytes);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while copying file " + ioe);
}
finally {
// close the streams using close method
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
}
}
This was an example of how to copy a binary file with streams in Java.

