如何只读取文件中的相关信息并忽略其他所有内容?
有人请编辑我的标题以使这个问题更清楚。
使用示例更容易显示:
myfile.txt 的内容:
10/05/2011: 10
10/05/2011: 45.4
10/05/2011: 12.1
我想读取日期后的数字( 10, 45.4, 12.1) 使用 BufferedReader 并存储在列表中。我该怎么做呢?我现在正在使用 readLine() 方法来读取数据,但读取整行。我不想在列表中存储日期,只想存储数字。是否可以?
Someone please edit my title to make this question more clear.
It's easier to show using an example:
Contents of myfile.txt:
10/05/2011: 10
10/05/2011: 45.4
10/05/2011: 12.1
I want to read the numbers after the date (10, 45.4, 12.1) using BufferedReader and store in a list. How would I do that? I am using readLine() method right now to read my data, but reads the entire line. I don't want to store date in my list, just the numbers. Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当然可以,尽管您必须先阅读整行,但完成后您可以编写一个简单的正则表达式来选择您想要的数字。
另外,由于数字总是在“:”之后,这也可以工作
Yes of course, although you will have to read the entire line first, once you have done that you can write a simple regular expression to pick what you want in this case numbers.
Alternatively since the numbers are always after ":", this will also work
比如:
......只需添加适当的错误检查......
Something like:
...just add proper error checking....
我无法编辑您的帖子,因为我没有足够高的权限,但是这个过程称为解析。
算法是
I am unable to edit your post because I do not have high enough privileges, however this process is called parsing.
The algorithm is
您可以使用 string 类的 subString 方法来获取所需的部分线。
例如。
或者您可以获取 ':' 的索引并将该索引用作 substring 方法的第一个参数。
You could use subString method of the string class to get the required part of the line.
For example.
Or you could get the index of ':' and use that index as the first parameter of the substring method.
检查 扫描仪,是否简单的。您可以使用 hasNext(String pattern) 方法。
Check the Scanner, is easy. You can especifiy a pattern to read what you need with the hasNext(String pattern) method .