「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

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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.println(resbyte);
}
}
}
}
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.println(resbyte); } } } }
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.println(resbyte);

                  }
            }

      }

}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
65
66
67
68
69
70
65 66 67 68 69 70
65
66
67
68
69
70

 

Java

Posted by arkgame