[英]How to run a exe file using Java
这是我的代码:
import java.io.IOException;
public class testv1 {
public static void main (String[] args) {
System.out.println("ABC");
try {
Process proc = Runtime.getRuntime()
.exec("D:\\Program\\Pyinstaller\\Merge\\Test\\dist\\helloworld.exe");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
我想运行 helloworld.exe 但它不起作用。 该程序只是打印
ABC
DONE
我也试过这个:
import java.io.File;
import java.io.IOException;
public class testv1 {
public static void main (String[] args) {
System.out.println("ABC");
try
{
Runtime.getRuntime().exec("D:\\Program\\Pyinstaller\\Merge\\Test\\dist\\helloworld.exe", null, new File("D:\\Program\\Pyinstaller\\Merge\\Test\\dist\\"));
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("Done");
}
}
但输出与前一个相同。
您可以使用工作目录执行进程:
exec(字符串命令,字符串[] envp,文件目录)
在具有指定环境和工作目录的单独进程中执行指定的字符串命令。
命令是 .exe envp 的位置可以是空目录,是您的 .exe 的目录就您的代码而言,它应该是...
Runtime.getRuntime().exec("c:\\program files\\test\\test.exe", null, new File("c:\\program files\\test\\"));
您可以使用 Runtime.exec(java.lang.String, java.lang.String[], java.io.File) 在其中设置工作目录。
或者,您可以按如下方式使用 ProcessBuilder:
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.directory(new File("myDir"));
Process p = pb.start();
从进程读取输出:
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.