我已经查找了如何通过运行时进程构建器在java中运行可执行文件,但它不起作用。我的代码如下...
String command = "potrace --svg mb-finer-19.pbm -o mb-finer-19.svg";
try {
File f = new File("C:\\webstudio\\potrace113win32");
Process process = Runtime.getRuntime().exec(command, null, f);
System.out.println("the output stream is " + process.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("The inout stream is " + s);
}
} catch (IOException e) {
e.printStackTrace();
}但是我回来了
java.io.IOException: Cannot run program "potrace" (in directory "C:\webstudio\potrace113win32"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at java.lang.Runtime.exec(Runtime.java:620)
at java.lang.Runtime.exec(Runtime.java:450)
at shellcommands.RunPotrace.main(RunPotrace.java:22)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
at java.lang.ProcessImpl.start(ProcessImpl.java:137)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)```根据javadoc的说法,我在哪里出了问题?可执行文件portace.exe和图像mb-finer-19.pbm都在目录中,非常感谢帮助。
发布于 2019-09-25 00:13:35
我运行了下面的代码,它成功了.
String command = "C:\\webstudio\\potrace113win32\\potrace.exe --svg mb-finer-19.pbm -o mb-finer-19.svg";显然,如果不在系统路径中,则必须指定整个路径。很抱歉在提出问题之前没有先尝试一下。
发布于 2019-09-25 00:51:21
下面是运行这样一个进程的正确方法:
Path imagesDir = Paths.get(
System.getProperty("user.home"), "Documents");
Path inputFile = imagesDir.resolve("mb-finer-19.pbm");
Path outputFile = imagesDir.resolve("mb-finer-19.svg");
ProcessBuilder builder = new ProcessBuilder(
"C:\\webstudio\\potrace113win32\\potrace.exe",
"--svg",
inputFile.toString(),
"-o",
outputFile.toString());
builder.inheritIO();
Process process = builder.start();
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new IOException("Got error code " + exitCode
+ " from command " + builder.command());
}inheritIO()将使子进程的所有子进程输出出现在调用它的Java程序的输出中,从而消除了自己使用进程的InputStream和ErrorStream的需要。
使用单个命令行参数而不是单个命令字符串的一个重要好处是,可以正确处理包含空格的文件名。这使得您的代码更容易移植,因为它可以处理任何有效的文件和任何有效的目录。
https://stackoverflow.com/questions/58084221
复制相似问题