Java FileOutputStream

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 144 of 306

What FileOutputStream Is

java.io.FileOutputStream writes raw bytes to a file. It's a subclass of OutputStream, the base class for every byte destination in Java, and the counterpart of FileInputStream.

Use it when the data isn't text or when you control the exact bytes yourself: saving downloaded files and uploads, copying files, writing images, audio, archives or any binary format. For text, use a writer (BufferedWriter, Files.writeString), which converts characters to bytes with a charset for you.

Writing Bytes

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Arrays;

public class O1 {
    public static void main(String[] args) throws IOException {
        try (FileOutputStream out = new FileOutputStream("bytes.bin")) {
            out.write(65);
            out.write(300);
            out.write(new byte[] {10, 20, 30});
            byte[] data = {1, 2, 3, 4, 5, 6};
            out.write(data, 2, 3);
            out.write("₹".getBytes(StandardCharsets.UTF_8));
        }
        System.out.println(Arrays.toString(Files.readAllBytes(Path.of("bytes.bin"))));

        try (FileOutputStream out = new FileOutputStream("bytes.bin")) {
            out.write(99);
        }
        System.out.println("after reopening: " + Arrays.toString(Files.readAllBytes(Path.of("bytes.bin"))));

        try (FileOutputStream out = new FileOutputStream("bytes.bin", true)) {
            out.write(100);
        }
        System.out.println("after append:    " + Arrays.toString(Files.readAllBytes(Path.of("bytes.bin"))));

        try {
            new FileOutputStream("no/such/folder/x.bin").close();
        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException: " + e.getMessage());
        }
    }
}

Output (on Linux):

[65, 44, 10, 20, 30, 3, 4, 5, -30, -126, -71]
after reopening: [99]
after append:    [99, 100]
FileNotFoundException: no/such/folder/x.bin (No such file or directory)

The write methods

MethodWrites
write(int b)One byte: the lowest 8 bits of b
write(byte[] b)The whole array
write(byte[] b, int off, int len)len bytes starting at index off

Walking through the first file:

  1. write(65) writes one byte with the value 65.
  2. write(300) writes 44, not 300. A byte can only hold 8 bits, so the higher bits are discarded: 300 is 1_0010_1100 in binary, and its lowest 8 bits 0010_1100 are 44. No exception is thrown, so passing a value outside 0–255 silently writes something else. This is a common bug when writing numbers to binary files — numbers larger than a byte must be split into several bytes explicitly, as the BMP example below does.
  3. write(new byte[] {10, 20, 30}) writes three bytes.
  4. write(data, 2, 3) writes 3 bytes starting at index 2: 3, 4, 5.
  5. Text must be converted to bytes with a charset first. "₹".getBytes(UTF_8) gives three bytes, which Arrays.toString prints as signed values (-30, -126, -71 are E2 82 B9).

Overwrite or append

  • new FileOutputStream(name) creates the file if needed, and truncates it if it already exists. Reopening the file and writing 99 replaced all eleven earlier bytes.
  • new FileOutputStream(name, true) opens the file in append mode: new bytes go at the end.

The constructors also accept a File (new FileOutputStream(file, true)).

Errors

The constructor throws FileNotFoundException when the file can't be opened for writing — here because the folder doesn't exist (FileOutputStream never creates parent folders), but also when the path is a folder or permission is denied. Create folders first with Files.createDirectories.

Copying a File with a Buffer

The most common use of FileOutputStream is the read-buffer-write loop: read a block from an input stream, write the same block to the output stream, repeat until the end.

import java.io.*;
import java.nio.file.*;
import java.util.Random;

public class Copy {
    static long copy(Path source, Path target, long reportEvery) throws IOException {
        long total = 0, nextReport = reportEvery;
        long size = Files.size(source);
        try (InputStream in = new FileInputStream(source.toFile());
             OutputStream out = new FileOutputStream(target.toFile())) {
            byte[] buffer = new byte[64 * 1024];
            int n;
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
                total += n;
                if (total >= nextReport || total == size) {
                    System.out.printf("  %3d%% (%,d of %,d bytes)%n", total * 100 / size, total, size);
                    nextReport += reportEvery;
                }
            }
        }
        return total;
    }

    public static void main(String[] args) throws IOException {
        byte[] video = new byte[1_000_000];
        new Random(42).nextBytes(video);
        Path src = Files.write(Path.of("lecture.mp4"), video);
        long copied = copy(src, Path.of("lecture-backup.mp4"), 300_000);
        System.out.println("copied " + copied + " bytes, identical: "
            + (Files.mismatch(src, Path.of("lecture-backup.mp4")) == -1));
    }
}

Output:

   32% (327,680 of 1,000,000 bytes)
   65% (655,360 of 1,000,000 bytes)
   91% (917,504 of 1,000,000 bytes)
  100% (1,000,000 of 1,000,000 bytes)
copied 1000000 bytes, identical: true

How it works:

  1. Test data. Random(42).nextBytes fills a megabyte with pseudo-random bytes, standing in for a video file. A fixed seed makes the run repeatable.
  2. Both streams in one try-with-resources. They're closed in reverse order — the output stream first, which completes the file, then the input stream — even if copying fails.
  3. out.write(buffer, 0, n) writes exactly the n bytes that were read. Writing the whole buffer instead would append stale bytes from the previous block at the end of the copy, producing a corrupted file that's slightly too large.
  4. Progress reporting. The copy runs in 64 KB blocks (65,536 bytes), so progress is printed at the first block boundary past each 300,000-byte step, and once more at 100%. Showing progress like this is the reason to write the loop yourself.
  5. Verification. Files.mismatch returns -1 when two files are byte-for-byte identical.

When you don't need progress or any processing of the bytes, the JDK does the same work in one call:

in.transferTo(out);                                         // stream to stream (Java 9+)
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); // file to file
Files.copy(inputStream, target);                            // e.g. an HTTP download or an upload to a file

Files.copy between two files can also use operating-system shortcuts that avoid copying data through Java at all.

Flushing and Syncing

FileOutputStream has no buffer of its own: each write call goes directly to the operating system. Its flush() method therefore does nothing. That has two consequences:

  • Many small writes (single bytes, small arrays) are slow, because each one is a system call. Wrap the stream in a BufferedOutputStream when writing in small pieces, as the BMP example does. A BufferedOutputStream does need flushing or closing, or its last bytes won't reach the file.
  • Once write returns, the data has been handed to the operating system, which normally writes it to disk shortly afterwards. If the data must be on the physical disk before your program continues — for example before reporting "payment recorded" — call out.getFD().sync(). This forces the operating system to write its cached data to the device. It's much slower, so use it only where durability really matters.

FileOutputStream and Files.newOutputStream

try (OutputStream out = Files.newOutputStream(Path.of("export.zip"))) { ... }
try (OutputStream out = Files.newOutputStream(Path.of("audit.bin"),
        StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { ... }

Files.newOutputStream returns an equivalent OutputStream for a Path, accepts open options such as CREATE_NEW (fail instead of overwriting) and throws NIO's more specific exceptions. Both are fine; Files.newOutputStream fits naturally into code that already uses Path.

Practical Example: Writing a Binary Image Format

Binary file formats define exactly which bytes go where. This example writes a valid BMP image — one of the simplest image formats — byte by byte, then reads it back with the JDK's image library to prove the file is correct. The same techniques apply to any binary format: fixed headers, multi-byte numbers in a specific byte order, and padding.

import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.*;
import javax.imageio.ImageIO;

public class Bmp {
    static void writeIntLE(OutputStream out, int v) throws IOException {
        out.write(v);
        out.write(v >>> 8);
        out.write(v >>> 16);
        out.write(v >>> 24);
    }

    static void writeShortLE(OutputStream out, int v) throws IOException {
        out.write(v);
        out.write(v >>> 8);
    }

    // pixels[row][col] = 0xRRGGBB, row 0 is the top row
    static void writeBmp(Path file, int[][] pixels) throws IOException {
        int height = pixels.length, width = pixels[0].length;
        int rowSize = (width * 3 + 3) / 4 * 4;          // each row is padded to a multiple of 4 bytes
        int imageSize = rowSize * height;
        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file.toFile()))) {
            out.write('B'); out.write('M');               // file header (14 bytes)
            writeIntLE(out, 14 + 40 + imageSize);         // total file size
            writeIntLE(out, 0);                           // reserved
            writeIntLE(out, 14 + 40);                     // offset of pixel data
            writeIntLE(out, 40);                          // info header size (40 bytes)
            writeIntLE(out, width);
            writeIntLE(out, height);
            writeShortLE(out, 1);                         // colour planes
            writeShortLE(out, 24);                        // bits per pixel
            writeIntLE(out, 0);                           // no compression
            writeIntLE(out, imageSize);
            writeIntLE(out, 2835);                        // 72 DPI horizontally
            writeIntLE(out, 2835);                        // 72 DPI vertically
            writeIntLE(out, 0);                           // palette colours
            writeIntLE(out, 0);                           // important colours
            for (int row = height - 1; row >= 0; row--) { // BMP stores the bottom row first
                for (int col = 0; col < width; col++) {
                    int rgb = pixels[row][col];
                    out.write(rgb);                       // blue
                    out.write(rgb >>> 8);                 // green
                    out.write(rgb >>> 16);                // red
                }
                for (int p = width * 3; p < rowSize; p++) out.write(0);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        int[][] flag = {
            {0xFF9933, 0xFF9933, 0xFF9933},
            {0xFFFFFF, 0x000080, 0xFFFFFF},
            {0x138808, 0x138808, 0x138808}};
        Path file = Path.of("flag.bmp");
        writeBmp(file, flag);
        System.out.println("file size: " + Files.size(file) + " bytes");

        BufferedImage img = ImageIO.read(file.toFile());
        System.out.printf("read back: %dx%d, top-left #%06X, centre #%06X, bottom-right #%06X%n",
            img.getWidth(), img.getHeight(),
            img.getRGB(0, 0) & 0xFFFFFF, img.getRGB(1, 1) & 0xFFFFFF, img.getRGB(2, 2) & 0xFFFFFF);
    }
}

Output:

file size: 90 bytes
read back: 3x3, top-left #FF9933, centre #000080, bottom-right #138808

The resulting flag.bmp opens in any image viewer as a tiny 3×3 tricolour. How the code produces valid bytes:

  1. Splitting integers into bytes. A BMP header stores numbers as 4-byte (and 2-byte) values in little-endian order — least significant byte first. writeIntLE writes v, then v >>> 8, v >>> 16 and v >>> 24. Each write(int) keeps only the lowest 8 bits, so each call outputs exactly one byte of the number. Here, the "only the lowest 8 bits" behaviour that silently produced 44 earlier is used on purpose.
  2. The headers. The file starts with the signature BM (the magic number checked by readers), then the total size, the position of the pixel data, and a 40-byte information header with width, height, 24 bits per pixel and no compression. The comments mark each field in the order the format specifies.
  3. Pixel order. Each pixel is written as blue, green, red — BMP's order, the reverse of the usual RGB notation. Rows are written bottom to top, so the loop starts at the last row.
  4. Row padding. Each row must occupy a multiple of 4 bytes. A row of 3 pixels is 9 bytes, so 3 zero bytes of padding are added, making 12. (width * 3 + 3) / 4 * 4 rounds up to the next multiple of 4 using integer division.
  5. Size check. 14 (file header) + 40 (info header) + 3 rows × 12 bytes = 90 bytes, matching the output.
  6. Buffering. The image is written in single bytes, so a BufferedOutputStream collects them and passes them to the FileOutputStream in large blocks. Closing it (by try-with-resources) flushes the last bytes; without that, the file would be incomplete.
  7. Verification. ImageIO.read parses the file with the JDK's own BMP decoder and returns the correct dimensions and colours, which confirms every byte is in the right place. getRGB returns the alpha channel in the top byte too, so & 0xFFFFFF keeps only the colour.

For formats with many numeric fields, the JDK can do the byte splitting for you. DataOutputStream (Data Streams lesson) writes numbers in big-endian order, which suits network protocols and Java's own formats but not BMP. ByteBuffer lets you choose: ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(v).array() produces the same four bytes as writeIntLE.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java FileOutputStream and get answers drawn from it.

Signed-in readers only.