Home Java Files Methods newOutputStream() Java Files newOutputStream() Method 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:
try (OutputStream out = Files.newOutputStream(path)) {
out.write(bytes);
}
Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND); Call What 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 public static OutputStream newOutputStream(Path path, OpenOption... options) throws IOException Parameters Parameter Description pathThe file to write. optionsOpen options; with none, CREATE, TRUNCATE_EXISTING, and WRITE.
Return Value Return Value Description OutputStreamAn open stream positioned at the start (or the end with APPEND).
Important
Throws NoSuchFileException if the parent folder is missing, FileAlreadyExistsException with CREATE_NEW, and IllegalArgumentException for READ or for APPEND combined with TRUNCATE_EXISTING. Data written through a wrapper such as GZIPOutputStream is only complete once the wrapper is closed.
Compare with Similar Methods Byte output:
Java Examples 1. Single bytes and arrays 2. Binary numbers 3. Compress on the fly Example 1 — Write Single Bytes and a Byte Array write(int) writes one byte; write(byte[]) writes them all.
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);
}
} Run with java NewOutputStreamBytes. The output is the same on Windows, macOS, and Linux.
Size: 6
Content: ABCDEF How It Works One byte at a time. write('A') passes the int 65 and writes its lowest 8 bits.A whole array. write(byte[]) adds the four bytes of CDEF.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.
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);
}
} Run with java NewOutputStreamData. The output is the same on Windows, macOS, and Linux.
Size: 12 bytes
int: 42
double: 1.5 How It Works 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.Close the outer stream. Closing the DataOutputStream also closes the file stream inside it.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.
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);
}
} Run with java NewOutputStreamGzip. The output is the same on Windows, macOS, and Linux.
Magic: 1f 8b
Unpacked: hello hello hello How It Works Layered streams. Text goes into the GZIP wrapper, which compresses it and passes the result to the file stream.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.Undo it. GZIPInputStream over newInputStream decompresses the bytes back into the original text.Frequently Asked Questions Is the stream from Files.newOutputStream buffered? No. Wrap it in a BufferedOutputStream, or write larger byte arrays, when making many small writes.
Does Files.newOutputStream overwrite an existing file? Yes. Without options it uses CREATE, TRUNCATE_EXISTING, and WRITE.
How do I append bytes to a file in Java? Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND).
Files.newOutputStream or FileOutputStream? Files.newOutputStream works with Path, accepts open options such as CREATE_NEW, and throws clearer exceptions.
Why is my GZIP file corrupt? The GZIPOutputStream was not closed, so the trailer was never written. Close the outermost stream, ideally with try-with-resources.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion