자바 shellExec()

1 개요[ | ]

자바 shellExec()
// String[] commands = { "bash", "-c", "echo hello" };
String[] commands = { "CMD", "/C", "echo hello" };
Process proc = Runtime.getRuntime().exec(commands);
BufferedReader brOut = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader brErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line;
List<String> outLines = new ArrayList<String>();
List<String> errLines = new ArrayList<String>();
while ((line = brOut.readLine()) != null) outLines.add(line);
while ((line = brErr.readLine()) != null) errLines.add(line);
String newline = System.getProperty("line.separator");
System.out.println("stdOut: " + String.join(newline, outLines));
System.out.println("stdErr: " + String.join(newline, errLines));
// stdOut: hello
// stdErr:
public static String shellExec(String command) {
	try {
		String[] commands = { "CMD", "/C", command };
		if( System.getProperty("file.separator") == "/" ) {
			commands = new String[] { "bash", "-c", command };
		}
		Process proc = Runtime.getRuntime().exec(commands);
		BufferedReader brOut = new BufferedReader(new InputStreamReader(proc.getInputStream()));
		BufferedReader brErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

		String line;
		List<String> outLines = new ArrayList<String>();
		List<String> errLines = new ArrayList<String>();
		while ((line = brOut.readLine()) != null) outLines.add(line);
		while ((line = brErr.readLine()) != null) errLines.add(line);
		String newline = System.getProperty("line.separator");
		return String.join(newline, outLines);
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}