![](/img/trans.png)
[英]How to read the last group of numbers on a line in a .txt file in Java
[英]program only read last line in .txt file java
我有问题,不知道该怎么办。 该方法应该读取.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;
}
这是因为当您使用read = x.next()
, read
对象中的字符串始终被文件下一行中的文本替换。 使用read += x.next()
或read = read.concat(x.next());
代替。
您可以将每个read替换为每个read()
。 另外,您没有close()
Scanner
。 我会使用“ try-with-resources
类的方法,
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.