누구나 DefaultExecutor
으로 실행되는 외부 프로그램의 출력을 스트리밍하는 방법에 대한 예제를 제공 할 수 있습니까? 이 작업을 수행하는 방법을 설명하는 설명서는 찾을 수 없습니다.commons-exec를 사용하여 스트리밍 출력 하시겠습니까?
외부 프로세스가 몇 시간 동안 실행되므로 모든 출력 데이터를 잡는 것만으로는 불가능합니다. 스트리밍해야합니다.
누구나 DefaultExecutor
으로 실행되는 외부 프로그램의 출력을 스트리밍하는 방법에 대한 예제를 제공 할 수 있습니까? 이 작업을 수행하는 방법을 설명하는 설명서는 찾을 수 없습니다.commons-exec를 사용하여 스트리밍 출력 하시겠습니까?
외부 프로세스가 몇 시간 동안 실행되므로 모든 출력 데이터를 잡는 것만으로는 불가능합니다. 스트리밍해야합니다.
참고 :이 솔루션은 동기식이므로 스트림되지 않습니다. 별도의 스레드에서 읽을 필요가 있거나 실행 명령의 비동기 버전을 사용해야합니다.
private InputStream getStream() {
String dataParsingCommand = "java";
PipedOutputStream output = new PipedOutputStream();
PumpStreamHandler psh = new PumpStreamHandler(output);
CommandLine cl = CommandLine.parse(command);
cl.addArgument("-jar");
cl.addArgument(dataParserPath);
DefaultExecutor exec = new DefaultExecutor();
DataInputStream is = null;
try {
is = new DataInputStream(new PipedInputStream(output));
exec.setStreamHandler(psh);
exec.execute(dataParserCommandLine);
} catch (ExecuteException ex) {
} catch (IOException ex) {
}
return is;
}
다음은 Runtime.exec을 사용하기위한 몇 가지 샘플 코드입니다. 그것을 당신의 사용에 적응시키는 것은 간단 할 것입니다.
import java.util.*;
import java.io.*;
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 class GoodWindowsExec
{
public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("USAGE: java GoodWindowsExec <cmd>");
System.exit(1);
}
try
{
String osName = System.getProperty("os.name");
String[] cmd = new String[3];
if(osName.equals("Windows NT"))
{
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
else if(osName.equals("Windows 95"))
{
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
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();
}
}
}
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4에서 편집 : 그것은 JDK 클래스를 사용하기 때문에이 정확히, 질문에 대답하지 않지만, 그것을 작동합니다.
)의 답변에 설명 된 이유로 작동하지 않습니다. 질문 ** commons-exec **를 사용하여 프로세스 호출을 수행하는 방법이었습니다.이 응답에 표시된 대부분의 항목을 래핑합니다. –
다른 질문 (http://stackoverflow.com/questions/2702834/commons-exec-hanging-when-i-call-executor-executecommandline –