Avoid creating FileStream directly

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: java-best-practices/avoid-filestream

Language: Java

Severity: Info

Category: Best Practices

Description

The classes that creates FileInputStream and FileOutputStream triggers too much garbage collection. Instead, use methods from the nio package that cause less garbage collection.

Learn More

Non-Compliant Code Examples

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");
    }
}

Compliant Code Examples

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)) {
        }
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: may/unit-testing