我已经用下面这个成语有一段时间了。这似乎是传播最广的,至少在我访问过的网站上。
在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();
}
}
我还不能评论其他条目,所以我就把它留在这里。
这里最好的答案之一(https://stackoverflow.com/a/326448/1521167):
private String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
仍然有一个缺陷。它总是在字符串末尾添加换行符,这可能会导致一些奇怪的错误。我的建议是将其更改为:
private String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int) file.length());
Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));
String lineSeparator = System.getProperty("line.separator");
try {
if (scanner.hasNextLine()) {
fileContents.append(scanner.nextLine());
}
while (scanner.hasNextLine()) {
fileContents.append(lineSeparator + scanner.nextLine());
}
return fileContents.toString();
} finally {
scanner.close();
}
}
如果您无权访问Files类,则可以使用本机解决方案。
static String readFile(File file, String charset)
throws IOException
{
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[fileInputStream.available()];
int length = fileInputStream.read(buffer);
fileInputStream.close();
return new String(buffer, 0, length, charset);
}
该代码将规范换行符,这可能是您真正想要做的,也可能不是。
这里有一个替代方案,它没有做到这一点,而且比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();
}
}
在扫描程序后按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会对你很刻薄,所以现在就要小心这些东西。
其他人已经给出了代码和东西,我不想抢走他们的荣耀