본문 바로가기

프로그래밍 언어/Java

Java) 자바로 shell script 실행하기

1. ShRunner class 만들기 

package ...;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class ShRunner {
	
    public Map<Integer, String> execCommand(String... str) {
        Map<Integer, String> map = new HashMap<>();
        ProcessBuilder pb = new ProcessBuilder(str);
        pb.redirectErrorStream(true);
        Process process = null;
        try {
            process = pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedReader reader = null;
        if (process != null) {
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        }

        String line;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            if (reader != null) {
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (process != null) {
                process.waitFor();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (process != null) {
            map.put(0, String.valueOf(process.exitValue()));
        }

        try {
            map.put(1, stringBuilder.toString());
        } catch (StringIndexOutOfBoundsException e) {
            if (stringBuilder.toString().length() == 0) {
                return map;
            }
        }
        return map;
    }

}

 

2. ShRunner 호출해서 사용하기 

import java.util.Map;

import replaceTest.ShRunner;

public class IOService {
	
	static ShRunner shRunner = new ShRunner();
	
	/**
	 * shell script 실행시키기 
	 * @param shFile
	 */
	 public void runShellScript(String shFile) {
		String cmds = "sh " + shFile;
        String[] callCmd = {"/bin/bash", "-c", cmds};
        Map<Integer,String> map = shRunner.execCommand(callCmd);
        System.out.println(map);
	}
}

References