「Java17」InputStreamReaderでファイルから1文字ずつ読み込む
環境
JDK17.0.4 2022-07-19
Eclipse 2022-06
Windows11 pro 64bit
構文
public int read() throws IOException
単一の文字を読み込みます。
オーバーライド:
read、クラス: Reader
戻り値:
読み込まれた文字。ストリームの終わりに達した場合は -1
条件
ファイル名 text.txt
ファイルの内容が下記文字です
ABCDEF
使用例
package com.arkgame.study;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class ArkgamecomDemo {
//ファイル名の変数の宣言
private static final String FILENAME = "C:\\study\\java\\test.txt";
//文字コード指定
private static final String CHARSET = "UTF-8";
public static void main(String[] args) throws IOException {
// try with resources
try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(FILENAME), CHARSET)) {
int resbyte;
while ((resbyte = inputStreamReader.read()) != -1) {
System.out.print("バイト");
System.out.print(resbyte);
System.out.print(" 文字");
//バイトデータをchar型に変換します
System.out.print((char) resbyte);
System.out.print("\n");
}
}
}
}
package com.arkgame.study;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class ArkgamecomDemo {
//ファイル名の変数の宣言
private static final String FILENAME = "C:\\study\\java\\test.txt";
//文字コード指定
private static final String CHARSET = "UTF-8";
public static void main(String[] args) throws IOException {
// try with resources
try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(FILENAME), CHARSET)) {
int resbyte;
while ((resbyte = inputStreamReader.read()) != -1) {
System.out.print("バイト");
System.out.print(resbyte);
System.out.print(" 文字");
//バイトデータをchar型に変換します
System.out.print((char) resbyte);
System.out.print("\n");
}
}
}
}
package com.arkgame.study; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class ArkgamecomDemo { //ファイル名の変数の宣言 private static final String FILENAME = "C:\\study\\java\\test.txt"; //文字コード指定 private static final String CHARSET = "UTF-8"; public static void main(String[] args) throws IOException { // try with resources try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(FILENAME), CHARSET)) { int resbyte; while ((resbyte = inputStreamReader.read()) != -1) { System.out.print("バイト"); System.out.print(resbyte); System.out.print(" 文字"); //バイトデータをchar型に変換します System.out.print((char) resbyte); System.out.print("\n"); } } } }
実行結果
バイト65 文字A
バイト66 文字B
バイト67 文字C
バイト68 文字D
バイト69 文字E
バイト70 文字F
バイト65 文字A
バイト66 文字B
バイト67 文字C
バイト68 文字D
バイト69 文字E
バイト70 文字F
バイト65 文字A バイト66 文字B バイト67 文字C バイト68 文字D バイト69 文字E バイト70 文字F