Avoid FileStream
ID |
java.avoid_filestream |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
efficiency |
Description
Reports direct instantiation of FileInputStream, FileOutputStream, FileReader or FileWriter. These legacy I/O classes have well-known drawbacks that the NIO java.nio.file.Files factories avoid.
Rationale
The java.io file stream classes (FileInputStream, FileOutputStream, FileReader, FileWriter) were introduced in JDK 1.0/1.1. They carry several problems:
-
They rely on finalization to release the underlying file descriptor. Until the finalizer runs, the descriptor stays open — under GC pressure this can exhaust the process’s fd limit and trigger
IOException: Too many open files. -
The
Reader/Writervariants read or write using the platform default charset. Code that works on a developer’s machine may silently corrupt data on a server with a different default. -
None of them provide buffering; a
read()/write()call typically translates to a system call.
// Bad — leaks descriptors under GC pressure, platform-default charset
InputStream in = new FileInputStream(file);
Reader r = new FileReader(file);
Remediation
Use the java.nio.file.Files factories: they return streams over a Path, are explicitly closeable (try-with-resources), and accept an explicit Charset for text I/O.
// Good — explicit charset, predictable close semantics
InputStream in = Files.newInputStream(path);
OutputStream out = Files.newOutputStream(path);
Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8);
Writer w = Files.newBufferedWriter(path, StandardCharsets.UTF_8);