Java基礎ーファイル入出力

ファイル入出力

1. ファイル入力

ファイル読み込みには以下の4種類のいずれかを使用する。

種類 説明
FileReader ファイルを1文字ずつ読み込む。Java11以降はエンコーディングを指定することができる。
BufferedReader FileReaderをラップするクラス。ファイルの内容を1行ずつ読み込む。
InputStreamReader InputStream から Reader への橋渡し。エンコーディングを指定できる
Files Java8で追加されたファイル操作のためのクラス。

○実装例

BufferedReader b = null;
try {
    File file = new File("inputfile/text.txt");
    b = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8));
    String str = b.readLine();
    while (str != null) {
        System.out.println(str);
        str = b.readLine();
    }
} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    try {
        if (b != null) {
            b.close();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

File file = new File("inputfile/text.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String str = br.readLine();
    while (str != null) {
        System.out.println(str);
        str = br.readLine();
    }
} catch (IOException e) {
    e.printStackTrace();
}

try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));) {
    String str;
    List<String> lines = new ArrayList<>();
    while ((str = reader.readLine()) != null) {
        lines.add(str);
    }
} catch (IOException e) {
    e.printStackTrace();
}

try {
    Path path = file.toPath();
    List<String> lines = Files.lines(path, StandardCharsets.UTF_8).collect(Collectors.toList());
    List<String> lines2 = Files.readAllLines(path, StandardCharsets.UTF_8);
    Files.write(path, lines2, null);
} catch (IOException e) {
    e.printStackTrace();
}

2. ファイル書き込み

ファイル書き込みには以下の4種類のいずれかを使用する。

種類 説明
FileWriter ファイルを1文字ずつ書き込む。Java11以降はエンコーディングを指定することができる
BufferedWriter FileWriterをラップするクラス。ファイルの内容を1行ずつ書き込む。
OutputStreamWriter OutputStream から Writerの橋渡し。エンコーディングを指定できる
Files Java8で追加されたファイル操作のためのクラス。

○実装例
基本的にはファイル読み込みと実装方法は同じ。

File file2 = new File("inputfile/sample.txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file2, true))) {
    bw.write("あいうえお");
} catch (IOException e) {
    e.printStackTrace();
}