Marcin
Marcin

Reputation: 513

parsing values from text file in java

I've got some text files I need to extract data from. The file itself contains around a hundred lines and the interesting part for me is:

AA====== test==== ====================================================/
AA    normal         low          max          max2         max3      /
AD     .45000E+01   .22490E+01   .77550E+01   .90000E+01   .47330E+00 /

Say I need to extract the double values under "normal", "low" and "max". Is there any efficient and not-too-error-prone solution other than regexing the hell out of the text file?

Upvotes: 2

Views: 121

Answers (3)

drew moore
drew moore

Reputation: 32670

If you really want to avoid regexes, and assuming you'll always have this same basic format, you could do something like:

HashMap<String, Double> map = new HashMap<>();
Scanner scan = new Scanner(filePath); //or your preferred input mechanism
assert (scan.nextLine().startsWith("AA====:); //remove the top line, ensure it is the top line

while (scan.hasNextLine()){
   String[] headings = scan.nextLine().split("\\s+"); //("\t") can be used if you're sure the delimiters will always be tabs
   String[] vals = scan.nextLine().split("\\s+");
   assert headings[0].equals("AA"); //ensure  
   assert vals[0].equals("AD"); 
   for (int i = 1; i< headings.length; i++){ //start with 1
       map.put(headings[i], Double.parseDouble(vals[i]);
   }
}
   //to make sure a certain value is contained in the map: 
   assert map.containsKey("normal");
   //use it:
   double normalValue = map.get("normal"); 
}

Code is untested as I don't have access to an IDE at the moment. Also, I obviously don't know what's variable and what will remain constant here (read: the "AD", "AA", etc.), but hopefully you get the gist and can modify as needed.

Upvotes: 2

tmanion
tmanion

Reputation: 401

If you know what index each value will start, you can just do substrings of the row. (The split method technically does a regex).

i.e.

 String normal = line.substring(x, y).trim();
 String low = line.substring(z, w).trim();

etc.

Upvotes: 0

chew socks
chew socks

Reputation: 1446

If each line will always have this exact form you can use String.split()

String line; // Fill with one line from the file
String[] cols = line.split(".")

String normal = "."+cols[0]
String low = "."+cols[1]
String max = "."+cols[2]

Upvotes: 0

Related Questions