Java – Using gnuplot with java

gnuplotjava

I'm using gnuplot with java and there is this problem that has been driving me crazy. Basically, I'm using this function to plot two double[] arrays on the same plot –

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

The idea is to write both doubles to separate files and plot them with gnuplot. When this function is called just once, it works just fine. But when I call it repeatedly from a loop, I see some empty files being produced and other files that are just wrong (for example, the plots decrease some times while I know they can't). It does work correctly in some cases, so this is very random. I know it has to do with the way I'm reading and writing the files before calling gnuplot. Can some one help me improve this plotting function so I don't see this odd behavior?

Best Answer

That looks like some kind of race condition, see Java: wait for exec process till it exits. Try the following:

Runtime commandPrompt = Runtime.getRuntime();
commandPrompt.exec("gnuplot auxfile.gp");
commandPrompt.waitFor();

This should wait for the gnuplot command to finish.