开发者

How do I execute an executable file from within a java file on linux?

开发者 https://www.devze.com 2023-03-31 20:55 出处:网络
I am trying to execute an executable file and a perl script from within a java program. I have found many topics similar to this but most of them refer to windows. I know java is platform independent

I am trying to execute an executable file and a perl script from within a java program. I have found many topics similar to this but most of them refer to windows. I know java is platform independent and it should work anyways but it doesn't. The solution I have tried already is the one based on the java Runtime and it's exec method. It works just fine on windows but since I'm porting my program on linux I need to adapt it. As I said I need to execute an executable file that I have compiled and was written in c++ which it looks like it's working but it finishes executing with an exit value of 1. I have no idea what it means but on windows it exits with 0 and that's how it should be on linux as well (?!?!). The pearl script on the other hand does not start at all. I use the command "perl script.pl" and it exits with a value of 255. Needless to say, it doesn't do what it's supposed to.

Does anybody know another way to execute these files? Or maybe where I am wrong with my implementation?

here's the code if you want to take a look at it: This is the one for the perl script开发者_如何学编程

public static void main(String[] args){
    System.out.println("Starting");
    try{
        String[] cmd = {"perl", "cloc-1.53.pl"};
        Process pr = Runtime.getRuntime().exec(cmd);
        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

        String line=null;

        while((line=input.readLine()) != null) {
            System.out.println(line);
        }

        int exitVal = pr.waitFor();
        System.out.println("Exit code: " + exitVal);
    } catch (Throwable t){
        t.printStackTrace();
    }
}

For the compiled file I change this:

String[] cmd = {"perl", "cloc-1.53.pl"};

with:

String cmd = "./UCC";


There should be no differece in starting processes on windows and linux.

Good article http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html Its for the old way but gives good insight.

Article converting to the new way:

From Runtime.exec() to ProcessBuilder

0

精彩评论

暂无评论...
验证码 换一张
取 消