「Java17」BufferedReaderクラスのreadLineメソッドでテキストファイルを1行ずつ読み込む
環境
JDK17.0.4 2022-07-19
Eclipse 2022-06
構文
1.public FileReader(File file) throws FileNotFoundException
読込み元のFileを指定して、新規FileReaderを作成します。
2.public BufferedReader(Reader in)
デフォルト・サイズのバッファでバッファリングされた、文字型入力ストリームを作成します。
3.public String readLine() throws IOException
テキスト行を読み込みます。1行の終端は、改行('\n’)か、復帰('\r’)、または復帰とそれに続く改行のいずれかで認識されます。
使用例
package com.arkgame.study;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TestDemo {
//ファイル名の変数の宣言
private static final String FILENAME = "C:\\study\\java\\test.txt";
static String TARGET = "study skill become smart";
public static void main(String[] args) throws IOException {
File flname = new File(FILENAME);
//読込み元のFileを指定
FileReader fileReader = new FileReader(flname);
//文字型入力ストリームを作成
BufferedReader bufferedReader = new BufferedReader(fileReader);
// readLineメソッドを使って1行ずつ読み込み表示
String line;
int i = 0;
while ((line = bufferedReader.readLine()) != null) {
i++;
System.out.println(i + "行目: " + line);
}
//リソースを開放します
bufferedReader.close();
}
}
実行結果
1行目: study skill
2行目: become smart
3行目: in arkgame