我在java中使用gnuplot,並且有這個問題一直讓我發瘋。基本上,我使用這個功能,在同一個情節繪製兩個雙[]數組 -與java一起使用gnuplot
public static void plot(String filename,double[] ua1,double[] ua2) throws IOException{
if(ua1.length==0 | ua2.length==0){
System.out.println("This one had no data - " + filename);
return;
}
File fold1 = new File("old");
if(fold1.exists()){
boolean a = fold1.delete();
if(!a)System.out.println("Houstoonnn!!!");
}
fold1 = new File("new");
if(fold1.exists()){
boolean a = fold1.delete();
if(!a)System.out.println("Not deleted!!!");
}
FileWriter outF1 = new FileWriter("old");
FileWriter outF2 = new FileWriter("new");
PrintWriter out1 = new PrintWriter(outF1);
PrintWriter out2 = new PrintWriter(outF2);
for(int j=0;j < ua1.length;j++){
out1.println(ua1[j]);
out2.println(ua2[j]);
}
out1.close();
out2.close();
File fold2 = new File("auxfile.gp");
try{//If the file already exists, delete it..
fold2.delete();
}
catch(Exception e){}
FileWriter outF = new FileWriter("auxfile.gp");
PrintWriter out = new PrintWriter(outF);
out.println("set terminal gif");
out.println("set output \""+ filename+".gif\"");
out.print("set title " + "\""+filename+"\"" + "\n");
out.print("set xlabel " + "\"Time\"" + "\n");
out.print("set ylabel " + "\"UA\"" + "\n");
out.println("set key right bottom");
out.println("plot \"old\" with linespoints,\"new\" with linespoints");
out.close();// It's done, closing document.
Runtime.getRuntime().exec("gnuplot auxfile.gp");
}
的想法是寫兩個雙打到單獨的文件,並與gnuplot的繪製出來。當這個函數被調用一次時,它就可以正常工作。但是當我從一個循環中重複調用它時,我會看到一些空文件正在生成,而其他文件只是錯誤的(例如,圖表會減少一些時間,而我知道它們不能)。它在某些情況下確實有效,所以這是非常隨機的。我知道它與我在調用gnuplot之前讀取和寫入文件的方式有關。有人可以幫助我改進這種繪圖功能,所以我沒有看到這種奇怪的行爲?
可能是某種競爭條件,請參閱[Java:等待執行過程直到它退出](http://stackoverflow.com/q/12448882/2604213)。 – Christoph
謝謝克里斯託弗。這正是問題所在。每次調用此函數後,我都添加了一個Thread.sleep(10),問題似乎已解決。 –