Backend/JAVA

[JAVA] 자바 외부 파일/ 외부 프로그램/ 명령어 실행 (exec)

dddzr 2023. 4. 26. 17:08

exec() 

exec() 메소드는 Runtime 클래스의 getRuntime() 메소드를 사용하여 Runtime 객체를 생성한 다음, Runtime 객체의 exec() 메소드를 호출하여 외부 프로그램을 실행합니다.
exec() 메소드는 실행할 외부 프로그램의 이름, 매개변수, 작업 디렉토리 등을 인자로 전달할 수 있습니다.

public Process exec(String command, String[] envp, File dir)

매개변수

command: 지정된 시스템 명령.
envp: 문자열 배열, 각 요소에 name=value 형식의 환경 변수 설정이 있거나 하위 프로세스가 현재 프로세스의 환경을 상속해야 하는 경우 null입니다.
dir: 하위 프로세스의 작업 디렉토리, 하위 프로세스가 현재 프로세스의 작업 디렉토리를 상속해야 하는 경우 null입니다.

 

- 외부 프로그램 실행

예를 들어, exec("cmd.exe /c dir")는 "cmd.exe" 프로그램을 실행하고 "/c" 옵션을 사용하여 "dir" 명령을 실행합니다.

 

- 외부 파일 실행

파일을 실행시키기 위해서도 exec() 메소드를 사용합니다.

제가 수정하던 코드는 지정된 위치에 있는 JAR 파일을 압축해제하여 해당 디렉토리에 있는 모든 클래스 파일을 추출하는 코드입니다.

batch 파일을 생성하여 실행시켰습니다.

기존 코드

    public int jarToClass(String serverPath, String fileName, String newServerFolderName) throwsIOException{
        File xfBatFile = newFile(serverPath + "WEB-INF/classes/class/xf.bat");
        BufferedWriter xfbufferedWriter = newBufferedWriter(newFileWriter(xfBatFile, false));
        String xfbatStr = "@echo off \n";
        xfbatStr += "pushd\"%~dp0\"\n";
        xfbatStr += "cd ../Project/" + newServerFolderName + "/WEB-INF/classes/class"+ "\n";
        xfbatStr += "setlocal\n";
        xfbatStr += "set STAServerWarFile=jar xvf " + fileName + ".jar *\n";
        xfbatStr += "%STAServerWarFile%\n";
        xfbufferedWriter.write(xfbatStr);
        xfbufferedWriter.flush();
        xfbufferedWriter.close();

        Runtime rt = Runtime.getRuntime();
        Process pro;
        String xfBatchFileName = serverPath + "WEB-INF/classes/class/xf.bat";
        try {
            pro = rt.exec(xfBatchFileName);
            pro.waitFor();

            return1;
        } catch (Exceptione) {
            e.printStackTrace();
            return0;
        }
    }

이 코드에서는 Runtime 객체를 생성하고, exec() 메소드를 사용하여 xfBatchFileName으로 지정된 외부 파일(xf.bat)을 실행합니다.

*-xvfM은 "eXtract Verbose File Manifest"의 약자로, JAR 파일을 압축해제하고 파일의 내용을 자세히 나열합니다.

 

- 명령어 수행

1차 수정

이 경우에는 굳이 파일을 만들지 않고 코드를 간단히 하기위해 command를 직접 실행하도록 수정했습니다.

    public int jarToClass(String filePath, String fileName) throws IOException{
        String javaBinPath = "\"C:\\Program Files\\Java\\jdk1.8.0_181\\bin\\";
        String jarCommand = javaBinPath + "jar.exe\" -xvfM " + filePath;
        Runtime rt = Runtime.getRuntime();
        Process pro;  
        try {
            pro = rt.exec(jarCommand);
            pro.waitFor();
            File jarFile = new File(filePath);
            jarFile.delete();
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

*jarCommand

jar.exe를 실행하고 JAR 파일을 -xvfM 옵션을 사용하여 압축해제합니다. 

 

최종코드

명령어 수행 후 만들어지는 파일 위치가 원하던 위치가 아니여서 2차로 수정했습니다.

명령어를 실행 할 때에도 실행 위치를 지정할 수 있습니다.

    public int jarToClass(String filePath, String fileName) throws IOException{
        String javaBinPath = "\"C:\\Program Files\\Java\\jdk1.8.0_181\\bin\\";
 	String jarCommand = javaBinPath + "jar.exe\" -xvfM " + fileName +".jar"
        File targetDir = new File(filePath.split(fileName)[0]);
        Runtime rt = Runtime.getRuntime();
        Process pro;  
        try {
            pro = rt.exec(jarCommand, null, targetDir);
            pro.waitFor();
            File jarFile = new File(filePath);
            jarFile.delete();
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }