0

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I've got an error Cannot find class File with your code above, line number 3. What does it mean??
Sounds like either testFile.class doesn't reside in the specified directory or is contained in a package or a class file that testFile requires is not in the class path...
I need to add import java.io.*;. Also need to escaped the directory slash to `\`. It works now thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.