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

在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();
    }
}

当前回答

自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

其他回答

您可以尝试扫描程序和文件类,几行解决方案

 try
{
  String content = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
  System.out.println(content);
}
catch(FileNotFoundException e)
{
  System.out.println("not found!");
}

使用前面评论中提到的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
}

基于扫描仪的非常精简的解决方案:

Scanner scanner = new Scanner( new File("poem.txt") );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block

或者,如果要设置字符集:

Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block

或者,使用trywithresources块,它将为您调用scanner.close():

try (Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" )) {
    String text = scanner.useDelimiter("\\A").next();
}

请记住,Scanner构造函数可以引发IOException。不要忘记导入java.io和java.util。

来源:Pat Niemeyer的博客

该代码将规范换行符,这可能是您真正想要做的,也可能不是。

这里有一个替代方案,它没有做到这一点,而且比NIO代码更容易理解(IMO)(尽管它仍然使用java.NIO.charset.charset):

public static String readFile(String file, String csName)
            throws IOException {
    Charset cs = Charset.forName(csName);
    return readFile(file, cs);
}

public static String readFile(String file, Charset cs)
            throws IOException {
    // No real need to close the BufferedReader/InputStreamReader
    // as they're only wrapping the stream
    FileInputStream stream = new FileInputStream(file);
    try {
        Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[8192];
        int read;
        while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
            builder.append(buffer, 0, read);
        }
        return builder.toString();
    } finally {
        // Potential issue here: if this throws an IOException,
        // it will mask any others. Normally I'd use a utility
        // method which would log exceptions and swallow them
        stream.close();
    }        
}

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

它有以下方法

public static String readFileToString(File file) throws IOException

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

public static List<String> readLines(File file) throws IOException