简体   繁体   English

从Java中的文件中读取特定行

[英]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. 我是一个相对较新的Java编程,我有一个我很难理解的任务。 Its is basically an I/O program with string manipulation. 它基本上是一个带字符串操作的I / O程序。

I have one input file, pb.txt, which looks like this; 我有一个输入文件,pb.txt,看起来像这样;

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. 打开文件pb.txt。
  • Read the string lines. 读取字符串行。
  • Extract the 5 winning numbers and the PB number 提取5个中奖号码和PB号码
  • Save them as integers n1, n2, n3, n4, n5, and pb. 将它们保存为整数n1,n2,n3,n4,n5和pb。
  • Assign an integer variable dateIndex for the date, which starts at 1 and is incremented by one for each date. 为日期指定一个整数变量dateIndex,从1开始,每个日期递增1。

Output the data file pbo.txt will look as follows: 输出数据文件pbo.txt将如下所示:

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 / O程序,但这对我来说很棘手。 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. 这是我第一次发布Stack Overflow,如果我做错了,请原谅我。

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. 如果文件很大,最好使用任何其他API逐行读取文件。

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 以下链接显示了与您的输入匹配的正则表达式示例: Regex

You cannot use it exactly as is, but it is a starting point. 你不能完全按原样使用它,但它是一个起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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