我遇到了问题,不知道该怎么做。该方法应该读取.txt文档中的所有文本。我的问题是当文档包含多行文本时,程序只读取最后一行。该计划不需要担心像这样的迹象。 ,:或空格,但必须阅读所有字母。有人能帮助我吗?
示例文字
你好,我的名字是 (返回正确的结果)你好我的
名称是
(仅返回名称)
private Scanner x;
String readFile(String fileName)
{
try {
x = new Scanner (new File(fileName + (".txt")));
}
catch (Exception e) {
System.out.println("cant open file");
}
while (x.hasNext()) {
read = x.next();
}
return read;
}
答案 0 :(得分:4)
这是因为当您使用read = x.next()
时,read
对象中的字符串始终被文件下一行中的文本替换。请改用read += x.next()
或read = read.concat(x.next());
。
答案 1 :(得分:1)
每次read()
替换每次阅读。另外,您没有close()
Scanner
String readFile(String fileName)
{
String read = "";
try (Scanner x = new Scanner (new File(fileName + (".txt")));) {
while (x.hasNextLine()) {
read += x.nextLine() + System.lineSeparator(); // <-- +=
}
} catch (Exception e) {
System.out.println("cant open file");
}
return read;
}
。我会使用try-with-resources
之类的东西,
{{1}}