【发布时间】:2017-06-19 22:36:43
【问题描述】:
在我的代码方法中,scanner.hasNext() 总是给出错误的结果。我在调试代码时理解它。有谁知道什么问题?我检查了文件。文件以字符串开头。
public class TextFileImplementor {
public static void main (String [] args){
System.out.println("Enter the name of file\n");
Scanner scanner = new Scanner(System.in);
File file = new File(scanner.nextLine());
try {
scanner = new Scanner(file);
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNext()){
stringBuilder.append(scanner.nextLine());
}
String [] strings = stringBuilder.toString().split("\\. ");
File newFile = new File("new_" + file.getName());
FileWriter fileWriter = new FileWriter(newFile, true);
for (String string :
strings) {
if (string.length()<141){
fileWriter.write(string + "\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
可能文件是空的?
-
如果您要致电
scanner.nextLine(),请联系scanner.hasNextLine()。不过,可能不是问题。 -
@AndyTurner,改为scanner.hasNextLine()。问题没有解决。
-
当我调试你的代码时,它读取文件中的行就好了。再看看你的输出代码和/或你的输入文件的内容。
-
@azurefrog ,现在我尝试使用不同的文件,有时它的工作。我猜它编码问题,我会尝试解决它。但数据不写入输出文件。我不明白为什么。