从java中的特定行读取文件到下一个特定行

时间:2015-02-28 08:34:52

标签: java io

我必须阅读以下数据:

追踪1:

数据

追踪2:

数据

追踪3:

数据

等等到文件的最后一个跟踪,其中数据是两列。我想将每个跟踪的数据添加到XYSeries。怎么做?我做了一些事情,但它读取了所有数据。如何在遇到下一个痕迹时拆分?

public static void main(String[] args) {
    String line;
    BufferedReader in = null;
    String temp [];
    try {
        in = new BufferedReader (new FileReader("data.txt"));
        //read until endLine
        while(((line = in.readLine()) != null)) {
            if (!line.contains("trace")) {
                //skipping the line that start with trace
                temp=(line.trim().split("[\\s]"));

                //YSeries series1 = new XYSeries("test");
    //series1.add(Double.parseDouble(temp[0]),Double.parseDouble(temp[1]))
            } 
        }   
    } catch (IOException ex) {
        System.out.println("Problem reading file.\n" + ex.getMessage());
    } finally {
        try { if (in!=null) in.close(); } catch(IOException ignore) {}
    }

}

2 个答案:

答案 0 :(得分:0)

一种方法是使用计数器:

String line;
String XY="";
Integer counter=0;
List<String> XYSeries =new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
      if(counter%2==0){
         XY=line;
      }
      else {
         XY=XY+line;
      } 
      XYSeries.add(XY);
      counter++;      
}
br.close();

答案 1 :(得分:0)

每次读取包含trace的行时,都可以初始化新的XYSeries。这样,当前的一个被添加到一个系列的列表中,另一个系列被创建用于下一​​个。

try {
    in = new BufferedReader (new FileReader("data.txt"));
    //read until endLine
    List<YSeries> seriesList = new ArrayList<>();
    YSeries currentSeries = null;
    while(((line = in.readLine()) != null)) {
        if (!line.contains("trace")) {
            //skipping the line that start with trace
            temp=(line.trim().split("[\\s]"));
            //no NullPointerException should be thrown because the file starts with a trace line but you may want to add a check, just in case
            currentSeries.add(Double.parseDouble(temp[0]),Double.parseDouble(temp[1])); 
        } else {
            //this is the start of a new trace series
            if (currentSeries != null) {
                seriesList.add(currentSeries);
            }
            currentSeries = new XYSeries(line);
        }
    }   
} catch (IOException ex) {
    System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
    try { if (in!=null) in.close(); } catch(IOException ignore) {}
}