开发者

How to read certain lines from a textfile using Java?

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 1

else if the first line has a time: do task 2

else if the first and second line are filled with times: do task 3

else if all three lines have times: do task 4

else 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.


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:

List<String> lines = new ArrayList<String>();

Scanner s = new Scanner(new File("filename.txt"));
while (s.hasNextLine())
    lines.add(s.nextLine());

switch (lines.size()) {
case 0: doTask1(); break;
case 1: doTask2(); break;
case 2: doTask3(); break;
case 3:
    if (gapBetween(lines.get(0), lines.get(2)) < 2)
        doTask4();
    else
        doTask5();
}


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.


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.

ArrayList<String> lines = new ArrayList<String>();
String line = null;
while ((line = inputFile.readLine()) != null){
lines.add(line);
}

Then you can do some if statements rather easily without overwriting previous lines in the buffer. (I am assuming that "inputFile" is a BufferedReader)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜