此代码将执行外部 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
还可以更轻松地处理可能包含空格的命令,而无需担心转义引号...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)