내 Java 프로그램이 여러 Unix 기반 시스템에서 echo "text" > /home/maxbester/test.txt
명령을 실행하도록합니다.Java - exec가 쉘처럼 작동하지 않습니다.
private static final Logger LOG = Logger.getLogger(MyClass.class);
public String run(String cmd) {
String res = null;
InputStream is = null;
try {
final Runtime rt = Runtime.getRuntime();
final Process p = rt.exec(cmd);
int exitStatus = -1;
try {
exitStatus = p.waitFor();
} catch (InterruptedException e) {
L0G.error(e.getMessage(), e);
}
is = p.getInputStream();
if (exitStatus == 0) {
if (is != null && is.available() > 0) {
StringWriter stringWriter = new StringWriter();
IOUtils.copy(is, stringWriter);
res = stringWriter.toString();
} else {
L0G.error("InputStream is not available!");
}
}
} catch (SecurityException e) {
L0G.error(e.getMessage(), e);
} catch (IOException e) {
L0G.error(e.getMessage(), e);
}
return res;
}
cmd를이 echo "text" > /home/maxbester/test.txt
에 해당하는 경우 및 파일 TEST.TXT가 존재 (, 그리고 echo "text" > /home/maxbester/test.txt
는가 disapeared 에코) 입술 "text" > /home/maxbester/test.txt
를 포함하고있는 test.txt이 비어 : 같은
내 코드 보인다. 그러나 종료 값은 0입니다 (올바르게 작동해야합니다).
나는 수동으로 echo "text" > /home/maxbester/test.txt
을 실행합니다. 아무 것도 반환되지 않고 종료 값도 0입니다.
그래서 exec 명령에 어떤 문제가 있습니까?
사실 특정 모드에서 프로그램은 JSch를 사용하여 원격 컴퓨터에서 작업을 수행합니다. 그래서'setCommand' 메소드 만 사용하여 작업을 할 수 있습니다. 나는 비슷한 행동을 원했다. – Maxbester