Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
862 views
in Technique[技术] by (71.8m points)

java Runtime.exec to run shell script - cannot open file

I am using Runtime.getRuntime().exec() to run a shell script from java code.

    String[] cmd = {"sh",  "build.sh", "/Path/to my/sh file"};
    try{
        Process proc = Runtime.getRuntime().exec( cmd );
    }
    catch(Exception e){
        System.out.println("Exception is:"+e);
    }

It gives me the following output in console:

sh: Can't open build.sh

Am I following some wrong approach here? Cannot make out why his happens.

EDIT

Based on the comment here, I have modified the String[] cmd = {"sh", "build.sh", "/Path/to my/sh file"}; to String[] cmd = {"sh", "/Path/to my/sh file/build.sh", "/Path/to my/sh file"}; . Now the problem is this script need to be executed from a particular path. When I execute this script from command prompt, I first change the directory to that path and execute it. How should I modify this code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a ProcessBuilder and set the working directory of the process to the directory where your script actually is:

final ProcessBuilder pb = new ProcessBuilder("/bin/sh", "script.sh", "whatever",
    "arguments", "go", "here");
pb.directory(new File("/path/to/directory"));
// redirect stdout, stderr, etc
final Process p = pb.start();

See the ProcessBuilder javadoc. It contains an example of what you can do. Runtime.exec() is passé :p


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...