I have to read a data look likes:
trace 1:
data
trace 2:
data
trace 3:
data
and so on upto last trace of file,where data is two column. I want to add the data for every trace to XYSeries. How to do that? i have done something but it reads all the data. how to split when it encounters next trace?
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) {}
}
}
one way is to use a counter:
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();
You could initialize a new XYSeries every time a line containing trace
is read. This way, the current one is added to a list a series and another series is created for the next one.
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) {}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.