3

What is the best practice for parsing these lines from a file?

files       txt 50     // first gab are spaces, the second is tabulator
files       bmp 9979
files       all 2063
score       scr 656
index       ind 0.0779
index       ind 0.0213 

I need to get just values (50, 9979, etc.) to be able to save them to CSV file (but this is not part of this question).

5 Answers 5

5

You could split by \s+ and accessing the last cell of the returned array.

for (String line : lines) {
    String[] data = line.split("\\s+");
    String lastEntry = data[data.length - 1];
    // lastEntry contains what you're looking for
}
Sign up to request clarification or add additional context in comments.

Comments

5

Is this what you want?

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
   String val = line.split("\\s+")[2];
   //do something with val

}
br.close();

Comments

2

This look like typical flat file. To read the number you should just move cursor for each line at the point of interest and read all character you need.

For your case you should start from 16 and read to the end of line.

1234567890123456
files       txt 50     
files       bmp 9979
files       all 2063
score       scr 656
index       ind 0.0779
index       ind 0.0213 

1 Comment

The op wrote about the structure. First are spaces then a tab.
2

Read each line using a FileReader then split the String by whitespace and retrieve the third index.

String value =line.split("\\s+")[2];

Comments

1

Read lines, iterate through them and use regex to split lines and get the values. That's it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.