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

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

当前回答

对于Java 7,这是我读取UTF-8文件的首选选项:

String content = new String(Files.readAllBytes(Paths.get(filename)), "UTF-8");

自Java7以来,JDK有了新的Java.nio.file API,它提供了许多快捷方式,因此简单的文件操作并不总是需要第三方库。


由于人们仍然对这个答案投赞成票,这里有一个在Java 11中引入的更好的解决方案:

String content = Files.readString(path);

其他回答

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

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

此外,如果您的文件恰好位于jar中,您也可以使用此选项:

public String fromFileInJar(String path) {
    try ( Scanner scanner 
            = new Scanner(getClass().getResourceAsStream(path))) {
        return scanner.useDelimiter("\\A").next();
    }
}

例如,如果您的jar是

my.jar/com/some/thing/a.txt

然后你想这样调用它:

String myTxt = fromFileInJar("/com/com/thing/a.txt");

使用JDK 8或更高版本:

未使用外部库

您可以从文件内容创建一个新的String对象(使用java.nio.file包中的类):

public String readStringFromFile(String filePath) throws IOException {
    String fileContent = new String(Files.readAllBytes(Paths.get(filePath)));
    return fileContent;
}

在一行(Java 8)中,假设您有一个Reader:

String sMessage = String.join("\n", reader.lines().collect(Collectors.toList()));

根据@erickson的回答,您可以使用:

public String readAll(String fileName) throws IOException {
    List<String> lines = Files.readAllLines(new File(fileName).toPath());
    return String.join("\n", lines.toArray(new String[lines.size()]));
}