Haeri
Haeri

Reputation: 701

Executing terminal commands from java

I know there are many threads about this, but none of them worked for me. Here is what I am trying to do:

Javac and run a file from my java code. It works for Windows but I would like to make it also work on UNIX. Here the code:

if(os.equals("win")){
        //For Windows
        try {
            Runtime.getRuntime().exec(
                            "cmd /c start cmd.exe /K "
                            + "\"cd " + path + "&& "
                            + "javac " + name + ".java && "
                            + "echo ^>^>" + name + ".java " + "outputs: &&"
                            + "echo. &&"
                            + "java " + name + " && "
                            + "echo. &&"
                            + "pause && "
                            + "exit\"");
        } catch (IOException e) {
            System.out.println("Didn't work");
        }
    }else{
        try {
            //TODO make it work for UNIX
            Runtime.getRuntime().exec("");
        } catch (IOException e) {
            System.out.println("Didn't work");
        }
    }

The problem is, that on UNIX systems it acts "unpredictable" For exemple:

Runtime.getRuntime().exec("open image.png");

Opens the image but

Runtime.getRuntime().exec("javac Test.java");
Runtime.getRuntime().exec("echo 'hello'");

It does nothing. No Massage.

I am grateful for any input.

UPDATE------------------------------------------------------------

It seems like in contrast to Windows CMD, Terminal needs a InputStreamReader to display what happened in exec. I found this code in another thread and now at least I get some output from the exec Terminal.

   String line;
   Process p = Runtime.getRuntime().exec( "echo HelloWorld2" );

   BufferedReader in = new BufferedReader(
           new InputStreamReader(p.getInputStream()) );
   while ((line = in.readLine()) != null) {
     System.out.println(line);
   }
   in.close();

But things still remain misterious, because executing

Process p = Runtime.getRuntime().exec("javac Test.java");

works and generates a Test.class file. But

Process p = Runtime.getRuntime().exec("javac Test.java && java Test");

does nothing.(Nothing happens. Terminal "executes" without error massages.) Typing this manually in Terminal builds and runs as expected. What am I missing?

Upvotes: 4

Views: 12759

Answers (1)

BarrySW19
BarrySW19

Reputation: 3819

I don't have a Linux system here to play with, but I'm pretty certain that the second command above is trying to compile Java files named "Test.java", "&&", "java" and "Test"; in other words the Runtime.exec() method treats arguments literally instead of applying shell interpretation.

You could probably get it to work with something along the lines of:

Process p = Runtime.getRuntime().exec(
    new String[] { "sh",  "-c", "javac Test.java && java Test" });

Upvotes: 2

Related Questions