我已经用下面这个成语有一段时间了。这似乎是传播最广的,至少在我访问过的网站上。

在Java中有没有更好/不同的方法将文件读入字符串?

private String readFile(String file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader (file));
    String         line = null;
    StringBuilder  stringBuilder = new StringBuilder();
    String         ls = System.getProperty("line.separator");

    try {
        while((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }

        return stringBuilder.toString();
    } finally {
        reader.close();
    }
}

当前回答

使用前面评论中提到的BufferedReader,但这种方式更可读:

String FILE_PATH = "filepath.txt";

try (FileReader fileReader = new FileReader(FILE_PATH)) {
    BufferedReader fileBufferReader = new BufferedReader(fileReader);
    String text = fileBufferReader.lines()
        .collect(Collectors.joining(System.lineSeparator()));
    System.out.println(text);
} catch (IOException e) {
    // exception handling
}

其他回答

自JDK 11以来:

String file = ...
Path path = Paths.get(file);
String content = Files.readString(path);
// Or readString(path, someCharset), if you need a Charset different from UTF-8

如果您正在寻找不涉及第三方库(例如Commons I/O)的替代方案,可以使用Scanner类:

private String readFile(String pathname) throws IOException {

    File file = new File(pathname);
    StringBuilder fileContents = new StringBuilder((int)file.length());        

    try (Scanner scanner = new Scanner(file)) {
        while(scanner.hasNextLine()) {
            fileContents.append(scanner.nextLine() + System.lineSeparator());
        }
        return fileContents.toString();
    }
}

如果是文本文件,为什么不使用apachecommons io?

它有以下方法

public static String readFileToString(File file) throws IOException

如果要将行作为列表,请使用

public static List<String> readLines(File file) throws IOException
Scanner sc = new Scanner(new File("yourFile.txt"));
sc.useDelimiter("\\Z");

String s = sc.next();

如果您需要字符串处理(并行处理),Java8有很棒的StreamAPI。

String result = Files.lines(Paths.get("file.txt"))
                    .parallel() // for parallel processing 
                    .map(String::trim) // to change line   
                    .filter(line -> line.length() > 2) // to filter some lines by a predicate                        
                    .collect(Collectors.joining()); // to join lines

JDK示例samples/lambda/BulkDataOperations中提供了更多示例,可以从Oracle Java SE 8下载页面下载

另一个单线示例

String out = String.join("\n", Files.readAllLines(Paths.get("file.txt")));