Home » Core Java » io » Copy binary file with streams

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

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 ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments