「Java17」FileInputStreamでテキストファイルを1行ずつ読み込む

環境
JDK17.0.4 2022-07-19
Eclipse 2022-06
Windows11 pro 64bit

構文
public InputStreamReader(InputStream in,Charset cs)
与えられた文字セットを使うInputStreamReaderを作成します。
パラメータ:
in – InputStream
cs – charset

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
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 (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
new FileInputStream(FILENAME), Charset.forName(CHARSET)))) {
String line;
int i = 0;
//テキスト行を読み込み
while ((line = bufferedReader.readLine()) != null) {
i++;
System.out.println(i + "行目: " + line);
}
}
}
}
package com.arkgame.study; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; 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 (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( new FileInputStream(FILENAME), Charset.forName(CHARSET)))) { String line; int i = 0; //テキスト行を読み込み while ((line = bufferedReader.readLine()) != null) { i++; System.out.println(i + "行目: " + line); } } } }
package com.arkgame.study;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

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 (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                        new FileInputStream(FILENAME), Charset.forName(CHARSET)))) {
                  String line;
                  int i = 0;
                  
                  //テキスト行を読み込み
                  while ((line = bufferedReader.readLine()) != null) {
                        i++;
                        System.out.println(i + "行目: " + line);
                  }
            }

      }

}

実行結果
1行目: 東京
2行目: 大阪
3行目: 福岡
4行目: 川崎

Java

Posted by arkgame