基本上,我有一个从 .txt 文件中读取多行的作业。 文本文件中每行有 4 个值,每个值之间用 2 个空格分隔。 文件中大约有10行数据。
从文件中获取输入后,程序将其放入数据库中。数据库连接功能运行良好。
我现在的问题是使用 BufferedReader 从文件中读取。 问题是,如果我取消注释底部 3 行中的任意 1 行,BufferedReader 会每隔一行读取一次。如果我不使用它们,那么就会出现异常,因为下一个输入是字符串类型。 我考虑过使用 Scanner 和 .hasNextLine() 方法。
对于可能出现的问题以及如何解决它有什么想法吗? 谢谢。
File file = new File(FILE_INPUT_NAME);
FileReader fr = new FileReader(file);
BufferedReader readFile = new BufferedReader(fr);
String line = null;
while ((line = readFile.readLine()) != null) {
String[] split = line.split(" ", 4);
String id = split[0];
nameFromFile = split[1];
String year = split[2];
String mark = split[3];
idFromFile = Integer.parseInt(id);
yearOfStudyFromFile = Integer.parseInt(year);
markFromFile = Integer.parseInt(mark);
//line = readFile.readLine();
//readFile.readLine();
//System.out.println(readFile.readLine());
}
编辑:.txt 文件的格式存在错误。缺失值。 但现在我得到了 ArrayOutOfBoundsException。
编辑编辑:.txt 文件中又出现错误!结果发现只有一个空格而不是两个空格。现在似乎正在发挥作用。但是对于将来如何处理此类文件错误有什么建议吗?
最佳答案
The issue is that if I uncomment any 1 of the 3 lines at the bottom the BufferedReader reads every other line.
正确。如果您放入任何这些代码行,则读取的文本行将被丢弃并且不会被处理。您已经在 while
条件下阅读。你不需要再读一遍。如果您放入任何这些行,它们将被丢弃并且不会继续
关于java - 使用 BufferedReader 从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42916413/