LoginSignup
66
52

More than 5 years have passed since last update.

【Java】テキストファイル全体を読み込み文字列を返すメソッド

Last updated at Posted at 2016-06-05

すぐに使える用。ただし、インポート宣言とメソッド定義は適切な場所に記述しなければならない。

// インポート宣言
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

// メソッド定義
public static String readAll(String path) throws IOException {
    StringBuilder builder = new StringBuilder();

    try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
        String string = reader.readLine();
        while (string != null){
            builder.append(string + System.getProperty("line.separator"));
            string = reader.readLine();
        }
    }

    return builder.toString();
}

JDK 8から追加されたStreamを使用することにより、コード量を半分ほど減らすことができました。

// インポート宣言
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

// メソッド定義
public static String readAll(String path) throws IOException {
    return Files.lines(Paths.get(path))
        .reduce("", (prev, line) ->
            prev + line + System.getProperty("line.separator"));
}

【2016/06/06追記】
上記のメソッドで1MBのテキストファイルを読み込むと、20秒以上かかります。コメントでのご指摘にある次のメソッドが最も高速でした。100MBのテキストファイルを1.3秒程で読み込むことができます。

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

public static String readAll(final String path) throws IOException {
    return Files.lines(Paths.get(path), Charset.forName("UTF-8"))
        .collect(Collectors.joining(System.getProperty("line.separator")));
}
66
52
6

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
66
52