经过一番测试,我发现在各种情况BufferedReader
下Scanner
都存在问题(前者经常无法检测到新行,而后者经常会去除空格,例如,从org.json库导出的 JSON 字符串中)。还有其他可用的方法,但问题是它们仅在某些 Java 版本之后才受支持(例如,这对 Android 开发人员不利),并且您可能不想仅出于这样的单一目的使用 Guava 或 Apache 公共库。因此,我的解决方案是将整个文件读取为字节并将其转换为字符串。下面的代码取自我的一个爱好项目:
/**
* Get byte array from an InputStream most efficiently.
* Taken from sun.misc.IOUtils
* @param is InputStream
* @param length Length of the buffer, -1 to read the whole stream
* @param readAll Whether to read the whole stream
* @return Desired byte array
* @throws IOException If maximum capacity exceeded.
*/
public static byte[] readFully(InputStream is, int length, boolean readAll)
throws IOException {
byte[] output = {};
if (length == -1) length = Integer.MAX_VALUE;
int pos = 0;
while (pos < length) {
int bytesToRead;
if (pos >= output.length) {
bytesToRead = Math.min(length - pos, output.length + 1024);
if (output.length < pos + bytesToRead) {
output = Arrays.copyOf(output, pos + bytesToRead);
}
} else {
bytesToRead = output.length - pos;
}
int cc = is.read(output, pos, bytesToRead);
if (cc < 0) {
if (readAll && length != Integer.MAX_VALUE) {
throw new EOFException("Detect premature EOF");
} else {
if (output.length != pos) {
output = Arrays.copyOf(output, pos);
}
break;
}
}
pos += cc;
}
return output;
}
/**
* Read the full content of a file.
* @param file The file to be read
* @param emptyValue Empty value if no content has found
* @return File content as string
*/
@NonNull
public static String getFileContent(@NonNull File file, @NonNull String emptyValue) {
if (file.isDirectory()) return emptyValue;
try {
return new String(readFully(new FileInputStream(file), -1, true), Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
return emptyValue;
}
}
您可以简单地使用getFileContent(file, "")
来读取文件的内容。