많은 다른 예제를 시도했지만 작동하지 않습니다.셸 스크립트를 실행하기 위해 자바 코드 샘플이 필요합니다.
셸 스크립트를 실행하기 위해 몇 가지 샘플 Java 코드를 사용 해줘서 고맙게 생각합니다.
많은 다른 예제를 시도했지만 작동하지 않습니다.셸 스크립트를 실행하기 위해 자바 코드 샘플이 필요합니다.
셸 스크립트를 실행하기 위해 몇 가지 샘플 Java 코드를 사용 해줘서 고맙게 생각합니다.
Runtime.getRuntime(). exec (...)가 필요합니다. a very extensive example을 참조하십시오 (처음 세 페이지를 읽는 것을 잊지 마십시오).
Runtime.exec은 입니다. 쉘이 아닙니다.; 당신이 쉘 스크립트를 실행하고자하는 경우 (나는/빈 경로에 항상 의심 있지만) 명령 줄 당신이 필요로하는 쉘 바이너리 완전한 이름입니다
/bin/bash scriptname
과 같을 것이다. 당신은
myshell> foo.sh
실행,
Runtime.getRuntime.exec("foo.sh");
또한 Runtime.exec의 당신이 첫 번째 예에서 실행중인 쉘에서 이미으로 실행하지만,하지 않을 경우 가정 할 수 없다.
A는 the previously mentioned article에서 예를 들어, mosly 잘라 내기 및 과거 (내 리눅스 머신 (TM)에서 작동을) 테스트 :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShellScriptExecutor {
static class StreamGobbler extends Thread {
InputStream is;
String type;
StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("USAGE: java ShellScriptExecutor script");
System.exit(1);
}
try {
String osName = System.getProperty("os.name");
String[] cmd = new String[2];
cmd[0] = "/bin/sh"; // should exist on all POSIX systems
cmd[1] = args[0];
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1]);
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(proc
.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(proc
.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
쉘 스크립트 test.sh 코드
#!/bin/sh
echo "good"
자바 코드에 쉘 스크립트 test.sh를 실행하십시오.
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]{"/bin/sh", "./test.sh"});
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
???? 당신은 더 명백 할 수 있습니까? – chburd
조금 더 컨텍스트가 좋을 것입니다, 예. – extraneon