sg552
sg552

Reputation: 1543

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?

Upvotes: 0

Views: 1830

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

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...

Upvotes: 3

Related Questions