「Java」FileReaderクラスでファイルを読み込むサンプル

書式
1.try (BufferedReader 変数名A = new BufferedReader(new FileReader(ファイル名)))
2.public FileReader(File file)throws FileNotFoundException
読込み元のFileを指定して、新規FileReaderを作成します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.spp;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathDemo {
private static final String strPath = "C:\\study\\java\\";
private static final String strFile = "sample.csv";
public static void main(String[] args) throws IOException {
Path target;
// ファイルのパスを取得
target = Paths.get(strPath, strFile);
// ファイルの情報
int i = 0;
try (BufferedReader rd = new BufferedReader(new FileReader(target.toFile()))) {
String strTxt;
while ((strTxt = rd.readLine()) != null) {
i++;
System.out.println(i + "行目 " + strTxt);
}
}
}
}
package com.arkgame.study.spp; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class PathDemo { private static final String strPath = "C:\\study\\java\\"; private static final String strFile = "sample.csv"; public static void main(String[] args) throws IOException { Path target; // ファイルのパスを取得 target = Paths.get(strPath, strFile); // ファイルの情報 int i = 0; try (BufferedReader rd = new BufferedReader(new FileReader(target.toFile()))) { String strTxt; while ((strTxt = rd.readLine()) != null) { i++; System.out.println(i + "行目 " + strTxt); } } } }
package com.arkgame.study.spp;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathDemo {

      private static final String strPath = "C:\\study\\java\\";
      private static final String strFile = "sample.csv";

      public static void main(String[] args) throws IOException {
            Path target;
            // ファイルのパスを取得
            target = Paths.get(strPath, strFile);
            // ファイルの情報
            int i = 0;
            try (BufferedReader rd = new BufferedReader(new FileReader(target.toFile()))) {
                  String strTxt;
                  while ((strTxt = rd.readLine()) != null) {
                        i++;
                        System.out.println(i + "行目 " + strTxt);
                  }

            }

      }

}

実行結果
1行目 1001,yamada,2021
2行目 1002,uemura,2022

Java

Posted by arkgame