简体   繁体   中英

Execute java file with Runtime.getRuntime().exec()

This code will execute an external exe application.

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());
    }     
} 

What if I want to execute external java file? Is it possible? For example like this command:

Runtime.getRuntime().exec("cmd.exe /C start cd \"C:\Users\sg552\Desktop\ java testfile");

The code does not work from java and cmd prompt. How to solve this?

First, you command line looks wrong. A execution command is not like a batch file, it won't execute a series of commands, but will execute a single command.

From the looks of things, you are trying to change the working directory of the command to be executed. A simpler solution would be to use ProcessBuilder , which will allow you to specify the starting directory for the given command...

For example...

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 also makes it easier to deal with commands that might contain spaces in them, without all the messing about with escaping the quotes...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM