此代码将执行外部 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
还可以更轻松地处理可能包含空格的命令,而无需担心转义引号...
关于java - 使用 Runtime.getRuntime().exec() 执行 java 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23716144/