使用扫描仪,我不知道如何读取多行文件并将其全部存储到字符串中。我使用如下循环:
while(file.hasNext())
{
string += file.nextLine();
}
我发现 file.hasNext 方法耗尽了文件中的所有数据,因此 file.nextInt() 没有任何要查找的值,因此它返回并出错。我可以做什么来“重置”扫描仪?我尝试创建一个新的 Scanner 对象,但这没有改变任何东西。我必须通过一种方法运行这个字符串,并且我已经多次遇到这个问题。我该怎么办?
最佳答案
也许你应该尝试 StringBuilder。
StringBuilder builder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
builder.append(line);
// process the line.
}
}
稍后
String text = builder.toString();
关于java - 如何将文件中的多行存储到扫描仪的字符串中`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36223089/