[java] java에서 shell script 실행하기

HI·2024년 9월 2일

java로 개발된 API에 python 소스를 실행할 부분이 있어서 찾아본 방법.
python 실행하는 shell 스크립트를 만들고 이를 java에서 실행!

   public static String doShellcommand(String value) throws Exception
        {
                Runtime runtime = Runtime.getRuntime();
                Process process = null;;
                String[] command={"/dir/쉘이름.sh",value};
                StringBuilder res = new StringBuilder();
                try{
                        process = runtime.exec(command);
                        BufferedReader in = new BufferedReader (new InputStreamReader(process.getInputStream()));
                        String line = null;
                        //실행한 shell 결과 읽기
                        while((line = in.readLine()) != null){
                                res.append(line);
                        }
                        in.close();
                }catch(Exception e){
                e.printStackTrace();
                }finally{
                        process.waitFor();
                        process.getErrorStream().close();
                        process.getInputStream().close();
                        process.getOutputStream().close();
                        process.destroy();
                }
                return res.toString();
    }

쉘을 실행하지 않고 다른 방법으로 https://d2.naver.com/helloworld/1113548 도 있다고 하니 다음에 참고해봐야겠다.

0개의 댓글