概要
FileInputStreamやらBufferedReaderStreamやらInputStreamReaderやら色々習ったが,結局どれを使うのがよいかわからなかったので調べた.
NIOおよびNIO2を利用すると簡単に書ける.
Oracleチュートリアル:ファイルI/O
[英語]https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
[日本語]https://docs.oracle.com/cd/E26537_01/tutorial/essential/io/fileio.html
NIO (New I/O) API
PathのファクトリクラスPathsとストリームのファクトリクラスFilesが重要.
JDK1.4でNIOが,JDK1.7でNIO2が追加された.
テキスト入力
1. 行ごとのストリームを取得したい場合
try (Stream<String> ss = Files.lines(Paths.get(filename))) {
ss.forEach(System.out::println);
} catch (IOException e) {
}
2. 1行ずつ読み込んで処理したい場合
try (BufferedReader br = Files.newBufferedReader(Paths.get(filename))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
}
テキスト出力
try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(filename));
PrintWriter pw = new PrintWriter(bw, true)) {
pw.println(str);
} catch (IOException e) {
}
備考
- Buffered系以外の入力ストリームは1行読み込みができない.