解析java中的文本文件中的值

时间:2014-05-30 18:15:06

标签: java text text-parsing

我有一些我需要从中提取数据的文本文件。文件本身包含大约一百行,对我来说有趣的部分是:

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

假设我需要在" normal"," low"下提取双值。和" max"。是否有任何有效且不太容易出错的解决方案,除了重新整理文本文件之外?

3 个答案:

答案 0 :(得分:2)

如果你真的想避免正则表达式,并假设你总是拥有相同的基本格式,你可以做类似的事情:

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

代码未经测试,因为我目前无法访问IDE。另外,我显然不知道变量是什么以及在这里保持不变(读取:&#34; AD&#34;,&#34; AA&#34;等等),但希望如此你得到了要点,可以根据需要进行修改。

答案 1 :(得分:0)

如果每一行都具有此确切形式,则可以使用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]

答案 2 :(得分:0)

如果你知道每个值将从哪个索引开始,你可以只做行的子串。 (拆分方法在技术上做了正则表达式。)

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