androniennn
androniennn

Reputation: 3137

How to retrieve a specified data from a File?

I'm storing this data in a .dat file:

data = date + ": " + y + "L/100KM "+ " " + value1 + "dt "+ value2 + "KM\n";

Every line has different values of date,y,value1 and value2. I want to retrieve variable value1 of every line. How to browse the file and extract this variable of all lines. I'm stucking in this problem in my project. Thanks for helping. EDIT: Example: I have this 3 datas stored in the file:

11/09: 5.8L/100KM 20dt 250KM
12/09: 6.4L/100KM 60dt 600KM
13/09: 7.5L/100KM 50dt 543KM

In that case, i want to retrieve 20dt, 60dt and 50dt.

Upvotes: 1

Views: 50

Answers (1)

aioobe
aioobe

Reputation: 420991

Here's one suggestion using regular expressions:

String line = "12/09: 6.4L/100KM 60dt 600KM";

Pattern p = Pattern.compile("(\\d+)dt");
Matcher m = p.matcher(line);

if (m.find())
    System.out.println(m.group(1));   // prints 60

If you have several lines to iterate over, you'd use for instance a new BufferedReader(new FileReader("youfile.dat")) and do something like

String line;
while ((line = br.nextLine()) != null) {
    Matcher m = p.matcher(line);
    if (m.find())
        process(m.group(1));
}

You could also just use line.split(" ") and select the 3:rd element:

String line = "12/09: 6.4L/100KM 60dt 600KM";
String dtVal = line.split(" ")[2];

// Optional: Remove the "dt" part.
dtVal = dtVal.substring(0, dtVal.length() - 2);

System.out.println(dtVal);

Upvotes: 2

Related Questions