解析文本文件数据

时间:2013-09-24 06:11:16

标签: java parsing text-files text-parsing

我有一个文本文件,其中包含以下文字:

VOLT=367
CURRENT=0.07
TEMP=031
RPM=3780
63HZ
VOLT=288
CURRENT=0.00
TEMP=030
RPM=3420
57HZ

等...... 我想将此文本文件作为输入在java中创建一个输出文本文件,其文本排列如下:

367,0.07,031,3780,63
288,0.00,030,3420,57

依此类推,直到txt文件结束..

到目前为止的编码尝试:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

try {
    FileInputStream fstream = new FileInputStream("file path\data.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    BufferedWriter brw = new BufferedWriter(new OutputStreamWriter(out));
    do {
        for (int i=1;i<50;i++) {
            //I dont know what to do here
            ...

2 个答案:

答案 0 :(得分:1)

试试这个,

String input = "";
br = new BufferedReader(new FileReader(inputFile));
out = new PrintWriter(outputFile);
StringBuilder result = new StringBuilder();
while ((input = br.readLine()) != null)
{
    if(input.contains("HZ"))
    {
        result.append(input.replace("HZ", ""));
        result.append("\n");
    }
    else
    {
        result.append(input.substring(input.indexOf("=") + 1, input.length()));
        result.append(",");
    }
}
System.out.println("result : "+result.toString());

答案 1 :(得分:0)

使用这个简单的代码。

String res="";
while ((input = br.readLine()) != null)
{
  if(input.indexOf("=")!= -1){
   res+=input.split("=+")[1]+",";
  }
  else{
    res+="\n";
  }
}
System.out.println("result : "+res.substring(0,res.length()-1));//To omit last ','