我试图从我的Java应用程序中解压rar文件。无法通过进程运行rar.exe
我发现了很多关于如何执行命令的解决方案,这些命令适用于Windows上的dir
等。但它似乎不适用于任何其他应用程序,如gcc
或rar
。我知道他们都工作,因为当我执行他们cmd
他们给我适当的输出。
但是,我想打印他们在cmd
中吐出的输出。我只是不明白为什么它适用于dir
,没有别的(没有“本地”命令)。
的exitVal
似乎总是0 ..
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("cmd /c rar.exe"); //Does not work
//Process pr = rt.exec("cmd /c dir") // This works
//Process pr = rt.exec("gcc.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
}catch(IOException e)
{
System.out.println("An error occured. Are you sure the executable is in your Windows PATH?");
}
catch(Exception e) {
System.out.println(e.me);
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
捕获errorstream的RAR的路径),它会告诉你,如果有什么不对的执行命令。 – Sanjeev
我喜欢A保罗的答案。现在你还必须考虑性能。如果你的代码将在WebServer上运行,或者至少有很多调用,那么使用一些java库会更好,使用'Runtime.exec()'调用外部程序可以杀死一个ApplicationServer(如果它是常用特性的一部分)。 .. – Martin