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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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.

Ilias Tsagklis

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


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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button