java - 如何使用 Java 运行 exe 文件
问题描述
这是我的代码:
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,文件目录)
在具有指定环境和工作目录的单独进程中执行指定的字符串命令。
command 是 .exe envp 的位置,可以是 null dir,是你的 .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();
推荐阅读
- java - 如何解决 - HTTP 状态 500 - Servlet 执行引发异常
- java - 不工作 spring.config.additional-location
- git - 将分叉 git 存储库的本地更改保留在 github 拉取请求之外
- python - 如何在 Python 中从 Elasticsearch 中获取所有结果
- python - python-hypothesis:检索或重新格式化一个伪造的例子
- amazon-web-services - 当多个网站托管在同一个存储桶中时,AWS CloudFront 正在下载文件
- python - alpine linux 上的 Python fbs - 缺少 PyQt 包
- spring-boot - 将程序参数传递给spring boot
- c++ - C++继承QHash不同的键类型
- c# - MVC路由如何检测文件路径