开发者

How to read only relevant information from a file and ignore everything else?

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 li开发者_Python百科st, just the numbers. Is it possible?


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];


Something like:

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

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

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


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);


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜