io
Copy binary file with streams
With this example we are going to demonstrate how to copy a binary file using theFileInputStream and theFileOutputStream. In short, to copy a binary file with streams you should:
- Create a newFileInputStream, by opening a connection to an actual file, the file named by the path source name in the file system.
- Create a newFileOutputStream 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 filewhile ((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 methodtry {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.
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!
We will contact you soon.
Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.




