Java Files newOutputStream() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, Files.newOutputStream(path) opens a file for writing and returns an OutputStream. It is the NIO.2 replacement for new FileOutputStream(file), and any API that writes to an OutputStream can write to it.

By default it creates the file or truncates it (CREATE, TRUNCATE_EXISTING, WRITE). The stream is not buffered, so wrap it in a BufferedOutputStream for many small writes.

A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.newOutputStream(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Open in try-with-resources, optionally with options:

Java
try (OutputStream out = Files.newOutputStream(path)) {
    out.write(bytes);
}
Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
CallWhat it does
Files.newOutputStream(p)Create or truncate, then write.
Files.newOutputStream(p, CREATE, APPEND)Write at the end.
new DataOutputStream(out)Write int, double, and so on.

Since Java 7. The underlying file is closed when the outermost wrapper stream is closed.

Library declarations
Java
public static OutputStream newOutputStream(Path path, OpenOption... options) throws IOException

Parameters

ParameterDescription
pathThe file to write.
optionsOpen options; with none, CREATE, TRUNCATE_EXISTING, and WRITE.

Return Value

Return ValueDescription
OutputStreamAn open stream positioned at the start (or the end with APPEND).

Compare with Similar Methods

Byte output:

MethodHow it differs
write()One byte[] in one call.
newInputStream()The reading counterpart.
newByteChannel()Write at any position.

Java Examples

Example 1 — Write Single Bytes and a Byte Array

write(int) writes one byte; write(byte[]) writes them all.

Java
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class NewOutputStreamBytes {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path file = dir.resolve("letters.txt");
        try (OutputStream out = Files.newOutputStream(file)) {
            out.write('A');
            out.write('B');
            out.write("CDEF".getBytes(StandardCharsets.US_ASCII));
        }
        System.out.println("Size: " + Files.size(file));
        System.out.println("Content: " + new String(Files.readAllBytes(file), StandardCharsets.US_ASCII));
        Files.delete(file);
        Files.delete(dir);
    }
}

How It Works

  1. One byte at a time. write('A') passes the int 65 and writes its lowest 8 bits.
  2. A whole array. write(byte[]) adds the four bytes of CDEF.
  3. Six bytes in total. Closing the stream finishes the file, which then holds ABCDEF.

Example 2 — Save Numbers with DataOutputStream

Wrap the stream to write an int and a double in binary form, then read them back with DataInputStream.

Java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class NewOutputStreamData {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path file = dir.resolve("numbers.bin");
        try (DataOutputStream out = new DataOutputStream(Files.newOutputStream(file))) {
            out.writeInt(42);
            out.writeDouble(1.5);
        }
        System.out.println("Size: " + Files.size(file) + " bytes");
        try (DataInputStream in = new DataInputStream(Files.newInputStream(file))) {
            System.out.println("int: " + in.readInt());
            System.out.println("double: " + in.readDouble());
        }
        Files.delete(file);
        Files.delete(dir);
    }
}

How It Works

  1. Fixed sizes. An int takes 4 bytes and a double 8, both in big-endian order, so the file is 12 bytes on every platform.
  2. Close the outer stream. Closing the DataOutputStream also closes the file stream inside it.
  3. Read in the same order. readInt then readDouble rebuild 42 and 1.5 exactly.

Example 3 — Write a GZIP File and Check Its Magic Bytes

Wrap the stream in GZIPOutputStream, inspect the first two bytes, then decompress to confirm the text.

Java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class NewOutputStreamGzip {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path gz = dir.resolve("notes.txt.gz");
        try (OutputStream out = new GZIPOutputStream(Files.newOutputStream(gz))) {
            out.write("hello hello hello".getBytes(StandardCharsets.UTF_8));
        }
        byte[] packed = Files.readAllBytes(gz);
        System.out.printf("Magic: %02x %02x%n", packed[0] & 0xFF, packed[1] & 0xFF);
        ByteArrayOutputStream plain = new ByteArrayOutputStream();
        try (InputStream in = new GZIPInputStream(Files.newInputStream(gz))) {
            byte[] buf = new byte[64];
            int n;
            while ((n = in.read(buf)) != -1) {
                plain.write(buf, 0, n);
            }
        }
        System.out.println("Unpacked: " + new String(plain.toByteArray(), StandardCharsets.UTF_8));
        Files.delete(gz);
        Files.delete(dir);
    }
}

How It Works

  1. Layered streams. Text goes into the GZIP wrapper, which compresses it and passes the result to the file stream.
  2. The GZIP signature. Every GZIP file starts with bytes 0x1f 0x8b. The compressed size is not printed because it can vary with the zlib version.
  3. Undo it. GZIPInputStream over newInputStream decompresses the bytes back into the original text.

Frequently Asked Questions

No. Wrap it in a BufferedOutputStream, or write larger byte arrays, when making many small writes.
Yes. Without options it uses CREATE, TRUNCATE_EXISTING, and WRITE.
Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND).
Files.newOutputStream works with Path, accepts open options such as CREATE_NEW, and throws clearer exceptions.
The GZIPOutputStream was not closed, so the trailer was never written. Close the outermost stream, ideally with try-with-resources.

Next: Files.notExists()

Check that a path definitely does not exist; false when unsure.

notExists() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful