使用Runtime.getRuntime()。exec()执行Java文件
此代码将执行一个外部exe应用程序。
private void clientDataActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
Runtime.getRuntime().exec("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe");
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
如果我想执行外部Java文件怎么办?可能吗?例如以下命令:
Runtime.getRuntime().exec("cmd.exe /C start cd \"C:\Users\sg552\Desktop\ java testfile");
该代码在java和cmd提示符下不起作用。如何解决呢?
-
首先,您的命令行看起来不正确。执行命令与批处理文件不同,它不会执行一系列命令,而只会执行一个命令。
从外观上看,您正在尝试更改要执行的命令的工作目录。一个更简单的解决方案是使用
ProcessBuilder
,它将允许您指定给定命令的起始目录…例如…
try { ProcessBuilder pb = new ProcessBuilder("java.exe", "testfile"); pb.directory(new File("C:\Users\sg552\Desktop")); pb.redirectError(); Process p = pb.start(); InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream()); consumer.start(); p.waitFor(); consumer.join(); } catch (IOException | InterruptedException ex) { ex.printStackTrace(); } //... public class InputStreamConsumer extends Thread { private InputStream is; private IOException exp; public InputStreamConsumer(InputStream is) { this.is = is; } @Override public void run() { int in = -1; try { while ((in = is.read()) != -1) { System.out.println((char)in); } } catch (IOException ex) { ex.printStackTrace(); exp = ex; } } public IOException getException() { return exp; } }
ProcessBuilder
还可以更轻松地处理可能在其中包含空格的命令,而不必将引号引起来。
-
尝试使用Runtime.getRuntime()。exec()执行Java jar
2021-01-30 关注 0 浏览97 1答案
-
使用Runtime.getRuntime()。exec从定义的目录中执行文件
2021-01-30 关注 0 浏览110 1答案
-
java Runtime.getRunTime()。exec和通配符?
2021-01-31 关注 0 浏览88 1答案
-
Runtime.getRuntime()。exec()
2021-01-31 关注 0 浏览100 1答案
-
Java-使用Runtime.getRuntime()。exec(无法启动临时文件启动的进程
2021-01-29 关注 0 浏览95 1答案
-
Runtime.getRuntime()。exec(cmd)挂起
2021-01-30 关注 0 浏览76 1答案
-
在Runtime.getRuntime()。exec中带有2个可执行文件的空格
2021-01-30 关注 0 浏览94 1答案
-
Java Runtime.getRuntime()。exec()调用数百次后失败
2021-01-30 关注 0 浏览97 1答案
-
使用System.setOut()重定向Runtime.getRuntime()。exec()输出;
2021-01-31 关注 0 浏览78 1答案
-
从Runtime.getRuntime()。exec()启动wkhtmltopdf:永不终止?
2021-01-30 关注 0 浏览89 1答案