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

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

当前回答

如果您愿意使用外部库,请查看ApacheCommonsIO(200KBJAR)。它包含一个org.apache.commons.io.FileUtils.readFileToString()方法,该方法允许您用一行代码将整个文件读取为字符串。

例子:

import java.io.*;
import java.nio.charset.*;
import org.apache.commons.io.*;

public String readFile() throws IOException {
    File file = new File("data.txt");
    return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}

其他回答

使用代码:

File file = new File("input.txt");
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
                file));
byte[] buffer = new byte[(int) file.length()];
bin.read(buffer);
String fileStr = new String(buffer);

fileStr包含字符串形式的输出。

此外,如果您的文件恰好位于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");

在扫描程序后按Ctrl+F键,我认为也应该列出扫描程序解决方案。最容易阅读的方式如下:

public String fileToString(File file, Charset charset) {
  Scanner fileReader = new Scanner(file, charset);
  fileReader.useDelimiter("\\Z"); // \Z means EOF.
  String out = fileReader.next();
  fileReader.close();
  return out;
}

如果您使用Java 7或更高版本(您确实应该),请考虑使用try with资源,以使代码更易于阅读。不要再把任何东西乱丢了。但我认为这主要是一种文体选择。

我发布这篇文章主要是为了完成主义,因为如果您需要经常这样做,java.nio.file.file中应该有一些东西可以更好地完成这项工作。

我的建议是使用File#readAllBytes(Path)获取所有字节,并将其输入到新的String(byte[]字符集)中,以从中获取一个您可以信任的String。在你的一生中,Charset会对你很刻薄,所以现在就要小心这些东西。

其他人已经给出了代码和东西,我不想抢走他们的荣耀

自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

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

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