Executing terminal commands from java

I know there is a lot about this, but none of them worked for me. Here's what I'm trying to do:

Javac and run the file from my java code. It works for Windows, but I would like it to work on UNIX as well. Here's 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 behaves "unpredictably" For example:

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

      

Opens an image, but

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

      

He does not do anything. No massage.

I am grateful for any input.

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

It looks like, unlike Windows CMD, Terminal needs an InputStreamReader to display what happened in exec. I found this code on another thread and now at least I am getting 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 everything still remains a motto because the fulfillment

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

works and generates Test.class file. But

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

doing nothing. (Nothing happens. The terminal "executes" without massaging errors.) Entering this manually in the terminal assembly and it works as expected. What am I missing?

+3


source to share


1 answer


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

You can probably make it work with something like this:



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

      

+1


source







All Articles