我必须在Java中读取一个文本文件,因为我使用的是以下代码:
Scanner scanner = new Scanner(new InputStreamReader(
ClassLoader.getSystemResourceAsStream("mock_test_data/MyFile.txt")));
scanner.useDelimiter("\\Z");
String content = scanner.next();
scanner.close();
据我所知String
有MAX_LENGTH 2^31-1
但是此代码仅从输入中读取前1024个字符 文件(MyFile.txt的)。
我无法找到原因。
答案 0 :(得分:1)
使用BufferedReader
的示例,适用于大文件:
public String getFileStream(final String inputFile) {
String result = "";
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader(inputFile)));
while (s.hasNext()) {
result = result + s.nextLine();
}
} catch (final IOException ex) {
ex.printStackTrace();
} finally {
if (s != null) {
s.close();
}
}
return result;
}
FileInputStream
用于较小的文件。
使用readAllBytes
并对其进行编码也可以解决问题。
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
您可以查看this问题。非常好。
答案 1 :(得分:1)
感谢您的回答:
最后我找到了解决方案 -
String path = new File("src/mock_test_data/MyFile.txt").getAbsolutePath();
File file = new File(path);
FileInputStream fis = null;
fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
content = new String(data, "UTF-8");
因为我必须立刻阅读一个很长的文件。
答案 2 :(得分:1)
我已经阅读了一些评论,因此我认为有必要指出这个答案并不关心好的或坏的做法。对于需要快速解决方案的懒人来说,这是一个愚蠢的好知的扫描技巧。
final String res = "mock_test_data/MyFile.txt";
String content = new Scanner(ClassLoader.getSystemResourceAsStream(res))
.useDelimiter("\\A").next();
被盗