현재 작은 Windows 배치 콘솔의 출력을 로그 파일로 리디렉션하는 데 문제가 있습니다. Java 응용 프로그램은 Runtime.exec() 호출을 끝내고 출력을 로그 할 때까지 기다리지 않고 시작해야합니다. 여기 내 로거 클래스는 다음과 같습니다시스템 호출 출력을 Java로 파일로 리디렉션
public class BatchThreadLogger extends Thread {
private Process process;
private String logFilePath;
private static final Logger logger = Logger.getLogger(BatchThreadLogger.class);
public BatchThreadLogger(Process process, String logFilePath) {
this.process = process;
this.logFilePath = logFilePath;
}
public void run() {
try {
// create logging file
File file = new File(logFilePath);
file.createNewFile();
// create a writer object
OutputStream os = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(os);
// catch the process output in an InputStream
InputStreamReader isr = new InputStreamReader(process.getInputStream());
BufferedReader br = new BufferedReader(isr);
// wait for the process to complete
int processStatus = process.waitFor();
// redirect the output to the log file
String line = null;
while ((line = br.readLine()) != null) {
pw.println(line);
}
// add a small message with the return code to the log
pw.println("********************************************");
pw.println("********************************************");
pw.println("Batch call completed with return status " + processStatus);
pw.flush();
os.close();
}
catch (IOException e) {
logger.error("IOException raised during batch logging on file " + logFilePath, e);
}
catch (InterruptedException e) {
logger.error("InterruptedException raised during batch process execution", e);
}
}
}
내 호출은 매우 간단합니다 :
Process process = Runtime.getRuntime().exec(command);
BatchThreadLogger logger = new BatchThreadLogger(process, logFilePath);
logger.start();
내 명령은 현재 두 매개 변수를 사용하여 내 TEST.BAT를 호출한다. 내 시험 배치는 이제 막 수행하지만 수행
echo "BATCH CALLED WITH PARAMETER %1 AND %2"
exit
내 로그 파일 만 포함
********************************************
********************************************
Batch call completed with return status 0
내가하지 않고, 전에 waitFor()
전화를 걸 시도하고 로그 파일에 출력을 리디렉션 코드 뒤에 성공. 나는 항상
답변에 대해 확실하지 않습니다. 배치 파일의 텍스트를 에코 처리하는 것이 오류로 간주되어 프로세스 실행의 오류 스트림에 어떻게 연결되는지 궁금합니다. 확실하게, 나는 getInputStream() 호출을 getErrorStream()으로 대체했지만 여전히 동작하지 않는다. 로그 파일에는 아무 것도 없다. ... – Wis
또한 무작위'ping www.google. ch' 에코 호출 후 에코 출력이 특수 스트림이나이 트릭으로 리다이렉트하지 않는지 확인하십시오. 로그에는 아무것도 표시되지 않습니다. BTW, 제가 게시 한 코드는 Linux에서 작동합니다. ProcessBuilder 제안에 관해서는'Runtime.exec()'호출을 쉽게 대체 할 수 있는지 알 수 있습니다. – Wis
존재하지 않거나 사용 권한 문제로 인해 읽을 수없는 배치 파일을 실행하려고하면 오류가 발생할 수 있습니다. 아직도 출력이 없다는 것은 이상하다. 'command' 변수에 정확히 무엇이 있는지 공유 하시겠습니까? 또한 어떤 종류의 응용 프로그램 (예 : 명령 줄, 웹 응용 프로그램, GUI, 서비스)이이 부분입니까? –