What do Java's FileInputStream and FileOutputStream do, and when would you use them rather than Files.newInputStream or Files.newOutputStream?
answer
- bytes through an open descriptor
- constructor opens the file
- truncate at open, or append flag
- no Java-side buffer on either API
- Path and open options versus File
basics
~20 sFileInputStream and FileOutputStream read and write raw bytes through an open file descriptor, unbuffered. Use them to wrap an existing FileDescriptor or to get getFD() from the stream; otherwise Files.newInputStream and newOutputStream take a Path and explicit open options.
solid answer
~50 s`FileInputStream` and `FileOutputStream` are the byte streams over a file: the constructor opens the file and holds a `FileDescriptor`, and every `read()` or `write(int)` goes to a native call with no buffer on the Java side, so a one-byte loop is slow unless you wrap the stream in a buffered one. `new FileOutputStream(name)` truncates at open; `new FileOutputStream(name, true)` appends; both create a missing file. `close()` releases the descriptor; the `Cleaner` registered when the constructor opened the file is a last resort that waits on GC. I default to `Files.newInputStream` and `Files.newOutputStream` because they take a `Path`, including one inside a zip file system, and spell out options such as `CREATE_NEW`, though they are not buffered either. I choose the older classes to wrap an existing `FileDescriptor`, when an API asks for them by type, or when I want `getFD().sync()` or `getChannel()` from the stream itself.
code
java · 22 linesimport java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
class AppendLog {
static void withFileOutputStream(byte[] line) throws IOException {
try (FileOutputStream out = new FileOutputStream("app.log", true)) {
out.write(line);
out.getFD().sync();
}
}
static void withFiles(byte[] line) throws IOException {
try (OutputStream out = Files.newOutputStream(Path.of("app.log"),
StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
out.write(line);
}
}
}go deeper
Recall that these two classes move raw bytes to and from a file, that the constructor opens it, and that a plain FileOutputStream wipes an existing file unless you pass true for append.
Explain the descriptor, the native call behind each read or write and why neither API buffers. Contrast the append flag with the APPEND option on a missing file, and say what the Cleaner does and does not do.
Show the judgment from production: truncation at open destroys data even when the write later fails, a descriptor leak waits on GC, and a dropped buffered wrapper loses bytes. Pick the API from what the code must express.
Treat it as a standards choice: default new code to Path and Files so it works across file systems with explicit open options, and keep the older classes where a descriptor or an API typed to them forces them.
## What the two classes are `java.io.FileInputStream` and `java.io.FileOutputStream` are the byte-stream classes that talk directly to a file. They extend `InputStream` and `OutputStream`, so they move **raw bytes**; the Javadoc of each points at `FileReader` or `FileWriter` for characters. Each instance holds a private `FileDescriptor` field, the JVM's handle on the operating system's open file. Constructing the stream is what opens the file: - `new FileInputStream(String)` or `(File)` opens an existing file for reading. A missing file, a directory, or any other failure to open gives `FileNotFoundException`. - `new FileOutputStream(String)` or `(File)` opens for writing and **truncates at open**: the old content is gone when the constructor returns, before any write. A missing file is created. - `new FileOutputStream(name, true)` sets the **append flag**: existing content stays, bytes go to the end of the file, and a missing file is still created. - `new FileInputStream(FileDescriptor)` and `new FileOutputStream(FileDescriptor)` wrap a connection that is already open. `System.out` is built on a `FileOutputStream` over `FileDescriptor.out`. The class Javadoc adds that some platforms let only one `FileOutputStream` at a time open a file for writing, and there the constructor fails if the file is already open. ## Nothing is buffered Neither class keeps a read or write buffer. `FileInputStream.read()` calls the private native `read0()` and `FileOutputStream.write(int)` calls a private native `write`, so a loop moving one byte at a time makes one native call per byte, which typically means one system call per byte. Loop `read()` over an 8 MiB file on a laptop and the bare stream takes a few seconds; the same loop through a `BufferedInputStream` takes tens of milliseconds. Bulk `read(byte[])` and `write(byte[])` avoid most of that cost. **`Files.newInputStream` costs the same.** Its Javadoc says the stream "will not be buffered", and the same goes for `Files.newOutputStream`. Moving to `Files` does not remove the need for a buffer, and the buffering decorators exist for both. ## Releasing the descriptor `close()` releases the descriptor and closes any `FileChannel` obtained from `getChannel()`. That is the normal path. If a stream is dropped unclosed, the `String` and `File` constructors have registered a package-private `FileCleanable`, a `PhantomCleanable<FileDescriptor>` run by a shared `Cleaner`, and a comment in it calls that close "last chance cleanup". What that means in practice: - **Timing belongs to the garbage collector.** The descriptor stays open until the collector finds the `FileDescriptor` phantom reachable, so a busy program can run out of descriptors first. - **It closes the raw descriptor and nothing else.** Bytes held by a `BufferedOutputStream` wrapped around the stream are not flushed; they are lost. - **A stream built on a `FileDescriptor` registers nothing itself.** Its constructor attaches to the descriptor it was given, and whoever opened that descriptor owns the cleanup. Both classes once declared `finalize` methods. Those were deprecated for removal in JDK 9 and removed in JDK 12, so the old advice to avoid these classes because of finalizers is out of date. ## Against the `Files` factories | Concern | `FileInputStream` / `FileOutputStream` | `Files.newInputStream` / `newOutputStream` | |---|---|---| | Opens from | `String`, `File`, `FileDescriptor` | `Path`, from the default or another provider | | Default write mode | Create or truncate | Create or truncate (`CREATE`, `TRUNCATE_EXISTING`, `WRITE`) | | Append | Flag; creates a missing file | `APPEND` alone fails on a missing file; add `CREATE` | | Fail if the file exists | No constructor offers it | `CREATE_NEW` | | Missing file on read | `FileNotFoundException` | `NoSuchFileException` on the default provider | | Buffered | No | No | | Descriptor or channel | `getFD()`, `getChannel()` | Declared `InputStream` / `OutputStream`, so neither | The `Path` row matters more than it looks. A `Path` inside a zip file system works with `Files`, while `Path.toFile()` throws `UnsupportedOperationException` for any provider but the default, so the older classes cannot open it. `Files` also documents its streams as safe for access by multiple concurrent threads. ## Choosing Default to `Files` in new code. The older classes still earn their place when: - an API asks for a `FileInputStream` or `FileOutputStream` by type; holding a `File` is no reason, since `file.toPath()` converts it; - you want the stream itself to expose `getFD().sync()` or `getChannel()`, though `FileChannel.open` gets a channel without them; - you need to wrap an already open descriptor, such as `FileDescriptor.out`. Either way, the choice does not decide buffering or the need to close: wrap for per-byte access, and close in try-with-resources.
- Does passing true for append to FileOutputStream behave like Files.newOutputStream(path, StandardOpenOption.APPEND)?Not on a missing file. The constructor creates it and appends; `APPEND` alone fails, with `NoSuchFileException` on the default provider. `Files.newOutputStream(path, CREATE, APPEND)` matches the constructor. For shared appends, `StandardOpenOption.APPEND` says atomic writes to the end are file system specific when other programs also write, and the `FileOutputStream` Javadoc promises nothing either.
- What happens when two FileInputStream objects share one FileDescriptor and you close one of them?Both streams attach to the descriptor, and `close()` runs the package-private `FileDescriptor.closeAll`, which closes every attached stream and then the descriptor. So after `new FileInputStream(in.getFD()).close()`, `in.read()` throws `IOException`. Nothing is reference counted, so only close a shared descriptor when every user is finished.
- Is the advice to avoid FileInputStream because of its finalizer still valid?No. It dates from when both classes declared `finalize` methods, which were deprecated for removal in JDK 9 and removed in JDK 12. The reasons to prefer `Files` today are about the API: a `Path` from any provider, explicit open options, and more specific exception types.
- FileInputStream buffers internally, so calling read() once per byte is cheap.
- Files.newInputStream is buffered, and that is why it beats FileInputStream.
- new FileOutputStream(path) truncates the file only when the first byte is written.
- The append flag on FileOutputStream fails if the file does not exist yet.
- Files.newOutputStream with APPEND alone creates a missing file, like the append flag.
- The Cleaner flushes and closes a forgotten stream promptly, so close() is optional.
- FileInputStream
- Java 1.0
- FileOutputStream
- Java 1.0
- FileOutputStream append flag
- Java 1.1
- Files.newInputStream and Files.newOutputStream
- Java 1.7
- java.lang.ref.Cleaner
- Java 9
Assumes JDK 27; FileInputStream and FileOutputStream read the same at JDK 25, and their finalize methods were removed in JDK 12.
context
- FileOutputStream.java at jdk-27-gagithub.com
- FileInputStream.java at jdk-27-gagithub.com
- Files (Java SE 27 & JDK 27)docs.oracle.com