Copy binary files such as images
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Showing steps for Windows. They are marked “On Windows” below.
A photo, a PDF or a ZIP file is copied correctly only when every byte arrives unchanged and in order. Byte streams do exactly that; text classes quietly change the bytes.
The buffer copy loop
A binary file stores bytes that are not meant to be read as text, such as an image, a PDF or a ZIP. Copy it with byte streams only: a Reader or Writer would change the bytes.
The buffer copy loop reads a block of bytes into a byte[], writes exactly the bytes it read, and repeats until read returns -1. A buffer of a few kilobytes, such as 8192 bytes, is a common choice.
Example 1 · Copy a photo with a buffer loop
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.nio.file.Files;import java.nio.file.Path;
public class BufferCopyDemo { static long copy(Path from, Path to) throws IOException { long total = 0; try (InputStream in = new FileInputStream(from.toFile()); OutputStream out = new FileOutputStream(to.toFile())) { byte[] buf = new byte[4096]; int n; while ((n = in.read(buf)) != -1) { out.write(buf, 0, n); total += n; System.out.println(" read " + n + " bytes"); } } return total; }
public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("photos"); Path photo = dir.resolve("photo.jpg"); byte[] data = new byte[10000]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i * 7); // stands in for real image bytes } Files.write(photo, data);
Path copy = dir.resolve("photo-copy.jpg"); long copied = copy(photo, copy); System.out.println("Copied " + copied + " bytes"); System.out.println(photo.getFileName() + ": " + Files.size(photo) + " bytes"); System.out.println(copy.getFileName() + ": " + Files.size(copy) + " bytes");
Files.delete(photo); Files.delete(copy); Files.delete(dir); }}read 4096 bytes read 4096 bytes read 1808 bytes Copied 10000 bytes photo.jpg: 10000 bytes photo-copy.jpg: 10000 bytes
What this code does
- 10,000 bytes with a 4096-byte buffer take three reads: two full blocks and a last block of 1808 bytes.
out.write(buf, 0, n)writes exactly the bytes that were read, so the copy has the same size as the original.
Example 2 · Bug: write(buf) adds stale bytes
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.nio.file.Files;import java.nio.file.Path;
public class StaleBytesDemo { public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("photos"); Path photo = dir.resolve("photo.jpg"); Files.write(photo, new byte[10000]); Path copy = dir.resolve("photo-copy.jpg");
try (InputStream in = new FileInputStream(photo.toFile()); OutputStream out = new FileOutputStream(copy.toFile())) { byte[] buf = new byte[4096]; while (in.read(buf) != -1) { out.write(buf); // bug: always writes 4096 bytes } } System.out.println("Original: " + Files.size(photo) + " bytes"); System.out.println("Copy: " + Files.size(copy) + " bytes"); System.out.println("First difference at byte " + Files.mismatch(photo, copy));
Files.delete(photo); Files.delete(copy); Files.delete(dir); }}Original: 10000 bytes Copy: 12288 bytes First difference at byte 10000
What this code does
- The loop ignores the count, so the last read of 1808 bytes is written as a full 4096-byte block: 3 × 4096 = 12288 bytes.
Files.mismatchreturns 10000 because the copy matches the original up to its end and then has 2288 extra bytes. Many viewers refuse such a file or show junk at the end.
The key line is out.write(buf, 0, n). The last block is usually smaller than the buffer, and writing the whole array would add stale bytes from the block before. Open both streams in one try-with-resources, so both files are closed even if the copy fails half way.
Find the bug
Find the copy bug
Each snippet copies a file. Tap the line that goes wrong.
The copy comes out bigger than the original.
Round 1 of 3Why a Reader corrupts an image
A Reader decodes bytes into characters with a charset. Image bytes are not text, so many of them are not valid UTF-8. The decoder replaces each bad byte with the replacement character U+FFFD (shown as �).
Example 3 · Copying an image through a Reader damages it
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.Reader;import java.io.Writer;import java.nio.charset.StandardCharsets;
public class ReaderDamageDemo { static String hex(byte[] b, int count) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; i++) { sb.append(String.format("%02X ", b[i])); } return sb.toString().trim(); }
public static void main(String[] args) throws IOException { byte[] png = new byte[264]; byte[] signature = { (byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n' }; System.arraycopy(signature, 0, png, 0, 8); for (int i = 8; i < png.length; i++) { png[i] = (byte) (i - 8); // every byte value 0 to 255 once }
ByteArrayOutputStream copy = new ByteArrayOutputStream(); try (Reader in = new InputStreamReader(new ByteArrayInputStream(png), StandardCharsets.UTF_8); Writer out = new OutputStreamWriter(copy, StandardCharsets.UTF_8)) { char[] buf = new char[1024]; int n; while ((n = in.read(buf)) != -1) { out.write(buf, 0, n); } } byte[] result = copy.toByteArray(); System.out.println("Original size: " + png.length + " bytes"); System.out.println("Copy size: " + result.length + " bytes"); System.out.println("Original starts: " + hex(png, 4)); System.out.println("Copy starts: " + hex(result, 4)); }}Original size: 264 bytes Copy size: 522 bytes Original starts: 89 50 4E 47 Copy starts: EF BF BD 50
What this code does
- The first PNG byte, 0x89, is not valid UTF-8 on its own, so the Reader turned it into the replacement character and the Writer saved that as the 3 bytes
EF BF BD. - The 128 bytes from 0x80 to 0xFF in the data met the same fate. Each of the 129 bad bytes became 3 bytes, so the copy grew from 264 to 522 bytes (264 + 129 × 2), and the original values cannot be recovered.
When a Writer encodes that character again, it writes 3 bytes (EF BF BD) in place of the 1 original byte. The copy becomes bigger, the original values are lost for good, and the image will not open. Plain English text survives the trip because its bytes are valid in UTF-8. That is why the bug often hides until someone copies a real photo.
InputStream and OutputStream, never Reader and Writer.transferTo and Files.copy
in.transferTo(out) (Java 9) runs the buffer copy loop for you and returns the number of bytes copied. You still open and close both streams yourself.
Example 4 · transferTo and Files.copy
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.nio.file.FileAlreadyExistsException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;
public class EasyCopyDemo { public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("certificates"); Path pdf = dir.resolve("certificate.pdf"); byte[] data = new byte[7000]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i % 251); } Files.write(pdf, data);
Path copy1 = dir.resolve("copy1.pdf"); try (InputStream in = Files.newInputStream(pdf); OutputStream out = Files.newOutputStream(copy1)) { System.out.println("transferTo copied " + in.transferTo(out) + " bytes"); }
Path copy2 = dir.resolve("copy2.pdf"); Files.copy(pdf, copy2); System.out.println("Files.copy made " + copy2.getFileName()); try { Files.copy(pdf, copy2); } catch (FileAlreadyExistsException e) { System.out.println("Second copy refused: " + copy2.getFileName() + " exists"); } Files.copy(pdf, copy2, StandardCopyOption.REPLACE_EXISTING); System.out.println("With REPLACE_EXISTING: done");
Path copy3 = dir.resolve("download.pdf"); try (InputStream download = new ByteArrayInputStream(data)) { // stands in for a network stream System.out.println("Saved stream: " + Files.copy(download, copy3) + " bytes"); }
for (Path p : new Path[] { copy1, copy2, copy3, pdf }) { Files.delete(p); } Files.delete(dir); }}transferTo copied 7000 bytes Files.copy made copy2.pdf Second copy refused: copy2.pdf exists With REPLACE_EXISTING: done Saved stream: 7000 bytes
What this code does
transferTois the copy loop in one call; the try-with-resources still opens and closes both streams.Files.copy(path, path)refuses to overwrite an existing file unless you passREPLACE_EXISTING.Files.copy(stream, path)saves a stream to a new file and returns the byte count.
Files.copy(source, target) copies a whole file from one Path to another in one call. It throws FileAlreadyExistsException if the target exists, unless you pass StandardCopyOption.REPLACE_EXISTING. Files.copy(inputStream, target) saves any stream, such as a download, straight to a file. Files.newInputStream(path) and Files.newOutputStream(path) are the modern way to open file streams from a Path; they behave like FileInputStream and FileOutputStream.
Checking the copy by size
Files.size(path) gives a file's size in bytes. Comparing the sizes of the original and the copy is the quickest check: a different size always means a broken copy.
On Windows
In PowerShell, Get-Item shows the size of a file in bytes. Compare the original and the copy before you trust the copy.
PS C:\Users\Priya\java-practice> Get-Item photo.jpg, photo-copy.jpg | Select-Object Name, LengthName Length ---- ------ photo.jpg 2048 photo-copy.jpg 2048
Example 5 · Verify a copy: size first, then content
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.Arrays;
public class VerifyCopyDemo { static String verify(Path original, Path copy) throws IOException { long a = Files.size(original); long b = Files.size(copy); if (a != b) { return "size differs: " + a + " vs " + b + " bytes"; } long position = Files.mismatch(original, copy); if (position != -1) { return "same size, but byte " + position + " differs"; } return "OK, all " + a + " bytes match"; }
public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("verify"); byte[] data = new byte[8000]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i * 13); } Path original = Files.write(dir.resolve("marksheet.png"), data); Path good = Files.copy(original, dir.resolve("good.png")); Path cut = Files.write(dir.resolve("cut.png"), Arrays.copyOf(data, 6000)); byte[] changed = data.clone(); changed[1234]++; Path flipped = Files.write(dir.resolve("flipped.png"), changed);
for (Path p : new Path[] { good, cut, flipped }) { System.out.println(p.getFileName() + ": " + verify(original, p)); Files.delete(p); } Files.delete(original); Files.delete(dir); }}good.png: OK, all 8000 bytes match cut.png: size differs: 8000 vs 6000 bytes flipped.png: same size, but byte 1234 differs
What this code does
- The size check is cheap and catches the cut copy at once, without reading any content.
flipped.pnghas the right size, so only the byte comparison withFiles.mismatchfinds the one changed byte at position 1234.
The same size does not prove the same content, because one changed byte keeps the size. Files.mismatch(a, b) (Java 12) compares the bytes and returns -1 when the files are identical, or the position of the first difference. For files on different computers, compare a checksum: a short number calculated from all the bytes, such as CRC32 or SHA-256. The module's practice lesson builds a simple one.
Next step
Check your understanding
11 quick questions