【问题标题】:Execute java file with Runtime.getRuntime().exec()使用 Runtime.getRuntime().exec() 执行 java 文件
【发布时间】:2014-05-17 21:15:20
【问题描述】:

此代码将执行外部 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 提示符下不起作用。如何解决?

【问题讨论】:

    标签: java runtime.exec


    【解决方案1】:

    首先,你的命令行看起来不对。执行命令不像批处理文件,它不会执行一系列命令,而是执行单个命令。

    从外观上看,您正在尝试更改要执行的命令的工作目录。一个更简单的解决方案是使用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 还可以更轻松地处理其中可能包含空格的命令,而无需担心转义引号...

    【讨论】:

    • 我在上面的代码中遇到错误Cannot find class File,第 3 行。这是什么意思??
    • 听起来testFile.class 没有驻留在指定的目录中,或者包含在testFile 所需的包或类文件中,而该类文件不在类路径中...
    • 我需要添加import java.io.*;。还需要将目录斜线转义为`\`。现在可以了,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 2012-05-28
    • 2012-06-21
    相关资源
    最近更新 更多