Avoid creating FileStream directly
Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel,
n'hésitez pas à nous contacter.
ID: java-best-practices/avoid-filestream
Language: Java
Severity: Info
Category: Best Practices
The classes that creates FileInputStream
and FileOutputStream
triggers too much garbage collection. Instead, use methods from the nio
package that cause less garbage collection.
class Main {
public static void main(String[] args) {
String filename = "/path/to/file.txt";
FileInputStream fis = new FileInputStream(filename);
FileOutputStream fos = new FileOutputStream(filename);
FileReader fr = new FileReader(filename);
FileWriter fw = new FileWriter(filename);
String s = new String("woeijf");
}
}
class Main {
public static void main(String[] args) {
String filename = "/path/to/file.txt";
try(InputStream is = Files.newInputStream(Paths.get(filename))) {
}
try(OutputStream os = Files.newOutputStream(Paths.get(filename))) {
}
try(BufferedReader br = Files.newBufferedReader(Paths.get(filename), StandardCharsets.UTF_8)) {
}
try(BufferedWriter wr = Files.newBufferedWriter(Paths.get(filename), StandardCharsets.UTF_8)) {
}
}
}