如何只读取文件中的相关信息并忽略其他所有内容?

发布于 2024-12-08 09:59:11 字数 298 浏览 0 评论 0原文

有人请编辑我的标题以使这个问题更清楚。

使用示例更容易显示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

情未る 2024-12-15 09:59:11

当然可以,尽管您必须先阅读整行,但完成后您可以编写一个简单的正则表达式来选择您想要的数字。

另外,由于数字总是在“:”之后,这也可以工作

String[] parts = myReadLine.split(":");
String numbers = parts[1];

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

String[] parts = myReadLine.split(":");
String numbers = parts[1];
篱下浅笙歌 2024-12-15 09:59:11

比如:

String number = br.readLine().split(":")[1];

......只需添加适当的错误检查......

Something like:

String number = br.readLine().split(":")[1];

...just add proper error checking....

柒七 2024-12-15 09:59:11

我无法编辑您的帖子,因为我没有足够高的权限,但是这个过程称为解析。

算法是

while(!EOF)
{
    //read until ':'
    //put chars after ':' into a string(or char[]) until you reach a \n
}

I am unable to edit your post because I do not have high enough privileges, however this process is called parsing.

The algorithm is

while(!EOF)
{
    //read until ':'
    //put chars after ':' into a string(or char[]) until you reach a \n
}
十年九夏 2024-12-15 09:59:11

您可以使用 string 类的 subString 方法来获取所需的部分线。

例如。

string line = readline()...;

string number = line.substring(12,14);

或者您可以获取 ':' 的索引并将该索引用作 substring 方法的第一个参数。

int i = line.indexOf(": ");
string number = line.substring(i, i+2);

You could use subString method of the string class to get the required part of the line.

For example.

string line = readline()...;

string number = line.substring(12,14);

Or you could get the index of ':' and use that index as the first parameter of the substring method.

int i = line.indexOf(": ");
string number = line.substring(i, i+2);
一身骄傲 2024-12-15 09:59:11

检查 扫描仪,是否简单的。您可以使用 hasNext(String pattern) 方法。

Check the Scanner, is easy. You can especifiy a pattern to read what you need with the hasNext(String pattern) method .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文