LoginSignup
8
4

More than 5 years have passed since last update.

Java で手軽にテキストファイルを読み込む (Java 11 & Java 7)

Posted at

概要

  • Java 11 環境では Files.readString と Path.of を使用
  • Java 7 環境では Files.readAllLines や Files.readAllBytes と Paths.get を使用

サンプルコード Cat.java

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Cat {

    public static void main(String[] args) throws IOException {
        String path = args[0];
        System.out.print(readString11(path));
        System.out.print(readString7(path));
        // String.join は Java 8 以降
        System.out.println(String.join(System.lineSeparator(), readLines7(path)));
    }

    /**
     * テキストファイルを読み込みます。Java 11 から使えるメソッド。
     * @param path 読み込むファイルのパス
     * @return ファイルの内容
     * @throws IOException
     * @throws OutOfMemoryError
     * @throws RuntimeException
     */
    public static String readString11(String path) throws IOException {
        return Files.readString(Path.of(path), Charset.forName("UTF-8"));
    }

    /**
     * テキストファイルを読み込みます。Java 7 から使えるメソッド。
     * @param path 読み込むファイルのパス
     * @return ファイルの内容
     * @throws IOException
     * @throws RuntimeException
     */
    public static String readString7(String path) throws IOException {
        return new String(Files.readAllBytes(Paths.get(path)), Charset.forName("UTF-8"));
    }

    /**
     * テキストファイルを読み込みます。Java 7 から使えるメソッド。
     * @param path 読み込むファイルのパス
     * @return ファイルの内容
     * @throws IOException
     * @throws RuntimeException
     */
    public static List<String> readLines7(String path) throws IOException {
        return Files.readAllLines(Paths.get(path), Charset.forName("UTF-8"));
    }
}

サンプル実行結果

コンパイル。

$ javac Cat.java

テキストファイルを用意。

$ cat sample.txt 
さんぷる
サンプル
SANNPURU

サンプルコードを実行。

$ java Cat sample.txt 
さんぷる
サンプル
SANNPURU
さんぷる
サンプル
SANNPURU
さんぷる
サンプル
SANNPURU

動作確認環境 

$ java -version
java version "11.0.1" 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)

$ uname -mrsv
Darwin 18.2.0 Darwin Kernel Version 18.2.0: Fri Oct  5 19:41:49 PDT 2018; root:xnu-4903.221.2~2/RELEASE_X86_64 x86_64

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.14.1
BuildVersion:   18B75

参考資料

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4