【发布时间】:2012-06-01 17:54:52
【问题描述】:
我在从 Java 运行 gnuplot 进程时遇到了一些问题。我正在创建一个 gnuplot 脚本文件,然后从 java 程序中运行它。我已经尝试使用 Process Builder 并使用 Runtime.getRuntime().exec("blah blah...") 构建一个进程,但都没有完全的工作能力。有趣的是,只要我通过 gnuplot 创建的图像文件没有保存到名称中没有空格的目录中,使用 Runtime 就可以使该过程几乎完美运行。然而,ProcessBuilder 根本不起作用,并给我错误:“CreateProcess error=2,系统找不到指定的文件”
我花了很长时间才弄清楚这些东西,所以任何帮助都将不胜感激。
我使用的代码在这里:
File script = new File("Demo.plt"); //Script file that outputs to a PNG file
//This works as long as the script file doesn't output to a png with a space in it's filepath
Process aProcess = Runtime.getRuntime().exec("gnuplot " + script.toString());
Thread.currentThread().sleep(1000);
aProcess.waitFor();
//This doesn't work at all
ProcessBuilder builder = new ProcessBuilder("gnuplot " + script.toString());
builder.redirectErrorStream(true);
Process process = builder.start();
而且我知道如果在 Java 之外运行脚本,无论输出行中的空格如何,该脚本都可以正常工作。我什至尝试过使用'\'(空格的转义字符),但这也不起作用。事实上,这是我使用的代码:
String graphName = "DemoGraph";
//Isolate the FilePath
String path = script.getPath();
path = path.replace(script.getName(),"");
path = path.replace(File.separator, "\\\\"); //Gets around any parsing errors in filepaths on Windows
path = path.replace(" ", "\\ "); //Should get around parsing errors with spaces in gnuplot, but it seems to be irrelevant.
scriptFileWriter.write("set output \"" + path + graphName + ".png\"\r\n");
这一定是java的问题,因为脚本从Windows命令行运行,从gnuplot命令行运行,并且通过双击运行frun
【问题讨论】:
-
您是否收到来自 gnuplot 的错误消息?除了“当我在路径名中有空格时,我想要的目录中没有 png 文件”之外,是否还有其他问题的症状。
-
另外,我不懂 Java,但你能打印字符串
"set output \"" + path + graphName + ".png\"\r\n"以便我们看看 gnuplot 到底看到了什么吗? -
这是字符串:'set output "C:\\Users\\toms\\Documents\\NetBeansProjects\\DRTTPS\\Simulation\Comparison\\DemoGraph.png"' 我没有得到我可以看到来自 Gnuplot 的任何错误消息,我不确定如何将其错误流转发到标准错误以便我可以看到它。实际上没有其他症状,除了它甚至没有创建目标文件。我之前遇到的其他错误让它创建了一个文件但没有写入它,但是这个错误并没有做到。
-
冒着说明显而易见的风险,但你确实有一个
scriptFileWriter.write声明,它实际上应该在你设置输出后绘制一些东西,对吗? -
您可以尝试的另一件事是将 gnuplot 脚本写入常规文件(例如 tmp.gnuplot.script),然后发出系统命令执行“gnuplot tmp.gnuplot.script”,然后查看如果那行得通。如果没有,那么您可以完整地发布 gnuplot 脚本,我们可以看看。
标签: java process gnuplot filepath processbuilder