如何使用 Java 从文本文件中读取某些行?
我有一个最多可以存储 3 行的文本文件(每行都有时间 ##:##)。
如果整个文本文件为空:执行 任务1
否则如果第一行有时间:执行 任务2
否则如果第一行和第二行是 充满时间:做任务3
否则如果所有三行都有时间:执行 任务4
否则如果所有三行都有时间但是 第一行时间和第三行时间 时间间隔超过2小时:做 任务5
我已经弄清楚了前两个。
if ((inputFile.readLine()) == null) {Keypad5 task1 = new Keypad5(); }
else if ((inputFile.readLine()) !=null) {Keypad6 task2 = new Keypad6();}
我如何阅读第二行和第三行?如果第二条线的时间是 12:54,而第三条线的时间是 3:55,那么这就是两个多小时的差距。我大概可以减去时间。
I have a text file that can store up to 3 lines (each line has time ##:##).
If the entire text file is empty : do
task 1else if the first line has a time: do
task 2else if the first and second line are
filled with times: do task 3else if all three lines have times: do
task 4else if all three lines have time but
the first line time and the third line
time have more than 2 hour gap: do
task 5
I have figured out the first two.
if ((inputFile.readLine()) == null) {Keypad5 task1 = new Keypad5(); }
else if ((inputFile.readLine()) !=null) {Keypad6 task2 = new Keypad6();}
How I can read and the second and third lines? And if second line has time 12:54, and third line has 3:55, this is more than 2 hour gap. I can subtract the times probably.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您在决定做什么之前先阅读所有三行内容。这将减少第二行和第三行的“复制和粘贴”阅读。
像这样的东西可能就是你所追求的:
I suggest you read in all three lines before deciding what to do. This would reduce "copying and pasting" reading of line two and three.
Something like this may be what you're after:
BufferedReader 上的后续 readLine() 调用始终读取文件的下一行。如果你想比较不同的行,你必须将它们存储在变量中,然后再进行比较。
subsequent readLine() calls on BufferedReader always read the next line of the file. If you want to compare different lines you have to store them in variables and compare them afterwards.
我会首先将所有文本行读入一个集合中,如果您相当确定这只是 3 行,那么它不会导致内存问题,并且您不需要进行太多错误处理。
然后,您可以相当轻松地执行一些 if 语句,而无需覆盖缓冲区中先前的行。 (我假设“inputFile”是一个 BufferedReader)
I would do this by first reading all of the lines of text into a Collection, if you are fairly sure this is only going to be 3 lines, it won't cause a memory issue and you don't need to do much error handling.
Then you can do some if statements rather easily without overwriting previous lines in the buffer. (I am assuming that "inputFile" is a BufferedReader)