晴耕雨読

working in the fields on fine days and reading books on rainy days

Javaで入出力(I/O)

Javaで入出力関連の関数・メソッドの一覧

ファイルから1行ずつ読み取り (readLine)

File file = new File("./test.txt");
try (BufferedReader f = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = f.readLine()) != null) {
      System.out.println(line);
    }
    // => Hello
    // => world!
} catch (IOException e1) {
    e1.printStackTrace();
}

Streamを使う場合:

File file = new File("./test.txt");
try (Stream<String> stream = Files.lines(file.toPath())) {
    stream.forEach(System.out::println);
    // => Hello
    // => world!
} catch (IOException e) {
    e.printStackTrace();
}

ファイル全体を一度に読み込む (readAllLines)

File file = new File("./test.txt");
try {
    List<String> list = Files.readAllLines(file.toPath());
    System.out.println(list);
    // => [Hello, world!]
} catch (IOException e) {
    e.printStackTrace();
}

ファイルへの書き込み (write)

File file = new File("./test.txt");
try (FileWriter f = new FileWriter(file)) {
    f.write("Hello\n")
    f.write("world!\n");
} catch (IOException e1) {
    e1.printStackTrace();
}

文字列の入力ストリームの生成 (StringReader)

StringReader input = new StringReader("Hello\nworld!");

try (BufferedReader f = new BufferedReader(input)) {
    String line;
    while ((line = f.readLine()) != null) {
        System.out.println(line);
    }
    // => Hello
    // => world!
} catch (IOException e1) {
    e1.printStackTrace();
}

文字列の出力ストリームの生成 (StringWriter)

try (StringWriter f = new StringWriter()) {
    f.write("Hello ");
    f.write("world!");

    System.out.println(f); // => hello world!
} catch (IOException e1) {
    e1.printStackTrace();
}