简体   繁体   中英

Read specific lines from a file in Java

I am relatively new to Java programming and I have an assignment which I am finding difficult to understand. Its is basically an I/O program with string manipulation.

I have one input file, pb.txt, which looks like this;

01/23/16  -22  32- 34- 40- 69  PB 19  X4  01/13/16  -27  29- 34- 41- 44  PB  2  X3  
01/20/16  -5  39- 44- 47- 69  PB 24  X5  01/09/16  -12  31- 43- 44- 57  PB 11  X2  
01/16/16  -3  51- 52- 61- 64  PB  6  X2  01/06/16  -6  37- 39- 45- 55  PB 33  X3

Here is the Problem statement;

  • Open the file pb.txt.
  • Read the string lines.
  • Extract the 5 winning numbers and the PB number
  • Save them as integers n1, n2, n3, n4, n5, and pb.
  • Assign an integer variable dateIndex for the date, which starts at 1 and is incremented by one for each date.

Output the data file pbo.txt will look as follows:

dateIndex  n1  n2  n3  n4  n5  pb

1   22  32  34  40  69  19

Note that spaces must separate the numbers.

I have done simple file I/O programs myself, but this one is tricky for me. I am unable to understand how I should separate the required lines from the file as there is other things written in the file as well, but I have to separate only the ones which are stated above. I appreciate any kind of help that I can get regarding this.

This is my first time posting on Stack Overflow so forgive me if I did something wrong.

Regards.

If the file is not too big, you can read all the lines as described in the accepted answer here .

If the file can be big, it would be better to use any other API to read a file line by line.

This first step shouldn't be so difficult.

On each line, you can then use a regular expression to find the necessary information.

The following link shows an example of a regular expression that matches your input: Regex

You cannot use it exactly as is, but it is a starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM