Jun 29

Java / Windows에서 Runtime.exec() 배치 리턴값이 정확히 넘어오지 않음

분류: Lang.Java 태그: ,Heart @ 1:58 오전

Trackback : http://dev.heartsavior.net/archives/150/trackback/

Java가 아무래도 OS depedent 한 부분은 좀 깔끔하지가 못한 게 아닌가 생각이 드는 상황.

Runtime.exec() -> Process.waitFor() 나 Process.exitValue();
배치 파일에서 넘겨주는 값과 상관없이 0이 나온다.

대놓고 배치 파일에

exit /b 1

을 해도 0 이 나온다. 당연히 cmd 창에서 배치를 실행하고 echo %ERRORLEVEL% 을 하면 1이 나온다.

음… 배치에서 리턴 값 받아서 쉽게 가려고 했는데 안될라나보다.

아래는 배치를 실행하는 클래스.
에러 코드 받아오는 것 빼고는 정상적으로 동작하는 것으로 보아서는 코드 문제 같지는 않다.

ps. 제가 뭔가 잘못 알고 있는 부분이 있거나, Java에서 리턴값을 받을 수 있는 방법이 있으면 알려주시면 정말 감사하겠습니다.

package net.heartsavior.dev.util;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
class ExecutorStreamRead extends Thread {
 
	private BufferedReader br = null;
 
	public ExecutorStreamRead(InputStream is) {
		br = new BufferedReader(
				new InputStreamReader(is) );
	}
 
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
 
		String line;
		try {
			while ((line = br.readLine()) != null) {
				// TODO 로그
				System.out.println(line);
			}
 
			br.close();
		} catch (IOException e) {
			// TODO 예외 처리
			e.printStackTrace();
		}
	}
 
}
 
/**
 * @author Heart
 *
 */
public class WindowsFileExecutor implements LocalFileExecutor {
	public int execute(String filePath, String argString) 
		throws IOException {
 
		if( null == filePath )
			return 0;
 
		Process p = null;
 
		String curDir = System.getProperty("user.dir");
		File workDir = null;
 
		if( filePath.indexOf(":") == -1 )		// 상대 경로
			workDir = new File(curDir + getDirectoryPath(filePath));
		else											// 절대 경로
			workDir = new File(getDirectoryPath(filePath));
 
		if( null != argString )
			p = Runtime.getRuntime().exec(
				getCorrectWindowsFilePath(filePath) + " " + argString, null, workDir);
		else
			p = Runtime.getRuntime().exec(getCorrectWindowsFilePath(filePath), null, workDir);
 
		// TODO 로그
		System.out.println("Console Print ------------------------");
 
		ExecutorStreamRead readStdout = new ExecutorStreamRead(p.getInputStream());
		readStdout.start();
 
		ExecutorStreamRead readStdErr = new ExecutorStreamRead(p.getErrorStream());
		readStdErr.start();
 
		// TODO 로그
		System.out.println("End of Console Print -----------------");
 
		int errorCode = -1;
 
		try {
			errorCode = p.waitFor();
		} catch(InterruptedException ie) {
			throw new IOException();
		}
 
		if( errorCode == 0 )
			errorCode = p.exitValue();
 
		return errorCode;
	}
 
	public static String getCorrectWindowsFilePath(String filePath) {
		if( -1 == filePath.indexOf(" ") )
			return filePath;
 
		StringBuffer sb = new StringBuffer();
		sb.append("\"");
		sb.append(filePath);
		sb.append("\"");
 
		return sb.toString();
	}
 
	public static String getDirectoryPath(String filePath) {
		char delim = '\\';
 
		int lastDelim = filePath.lastIndexOf(delim);
 
		if( -1 == lastDelim ) {
 
			delim = '/';
 
			lastDelim = filePath.lastIndexOf(delim);
 
			if( -1 == lastDelim)
				return null;
		}
 
		return filePath.substring(0, lastDelim);
	}
}

4 Responses to “Java / Windows에서 Runtime.exec() 배치 리턴값이 정확히 넘어오지 않음”

  1. TheFrenzy says:

    안녕하세요.
    링크 추가했어요~ 방명록이 없네요…
    -DC

  2. Heart says:

    TheFrenzy//
    반가워요 :)
    제 ‘평소’ 블로그는 http://www.heartsavior.net 에 있어요
    방명록도 당연 거기 있겠죠? ^^;;
    안내 페이지를 하나 만들어야겠다 생각했는데 계속 까먹고 있었네요. ㅎㅎ

  3. sloth says:

    잘봤어요^^

  4. Heart says:

    sloth//
    방문 감사합니다 :)

Leave a Reply