"자바 shellExec()"의 두 판 사이의 차이

잔글 (봇: 자동으로 텍스트 교체 (-</source> +</syntaxhighlight>, -<source +<syntaxhighlight ))
 
2번째 줄: 2번째 줄:
;자바 shellExec()
;자바 shellExec()


<source lang='java'>
<syntaxhighlight lang='java'>
// String[] commands = { "bash", "-c", "echo hello" };
// String[] commands = { "bash", "-c", "echo hello" };
String[] commands = { "CMD", "/C", "echo hello" };
String[] commands = { "CMD", "/C", "echo hello" };
18번째 줄: 18번째 줄:
// stdOut: hello
// stdOut: hello
// stdErr:
// stdErr:
</source>
</syntaxhighlight>
<source lang='java'>
<syntaxhighlight lang='java'>
public static String shellExec(String command) {
public static String shellExec(String command) {
try {
try {
42번째 줄: 42번째 줄:
return null;
return null;
}
}
</source>
</syntaxhighlight>


==같이 보기==
==같이 보기==

2020년 11월 2일 (월) 02:49 기준 최신판

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 }}