Java Runtime.getRuntime(): 명령줄 프로그램을 실행하여 출력을 가져옵니다.
Java 프로그램에서 명령 프롬프트 명령을 실행하기 위해 실행 시간을 사용하고 있습니다.그러나 명령어가 반환하는 출력을 어떻게 얻을 수 있는지 알 수 없습니다.
코드는 다음과 같습니다.
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send" , argument};
Process proc = rt.exec(commands);
하려고 했는데System.out.println(proc);
하지만 그것은 아무것도 돌려주지 않았다.이 명령어를 실행하면 세미콜론으로 구분된2개의 숫자가 반환됩니다.출력할 변수를 어떻게 만들 수 있을까요?
현재 사용하고 있는 코드는 다음과 같습니다.
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);
InputStream stdIn = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdIn);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<OUTPUT>");
while ((line = br.readLine()) != null)
System.out.println(line);
System.out.println("</OUTPUT>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
하지만 출력으로 아무것도 얻을 수 없지만 직접 명령어를 실행하면 정상적으로 작동합니다.
방법은 다음과 같습니다.
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
자세한 내용은 여기를 참조하십시오. ProcessBuilder
사용하기에 좋은 선택일 것입니다.
보다 빠른 방법은 다음과 같습니다.
public static String execCmd(String cmd) throws java.io.IOException {
java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
이는 기본적으로 이를 요약한 것입니다.
public static String execCmd(String cmd) throws java.io.IOException {
Process proc = Runtime.getRuntime().exec(cmd);
java.io.InputStream is = proc.getInputStream();
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
String val = "";
if (s.hasNext()) {
val = s.next();
}
else {
val = "";
}
return val;
}
오래된 질문인 건 알지만 이게 더 빠를 것 같아서 올렸습니다.
편집(Java 7 이상용)
스트림 및 스캐너를 닫아야 합니다.깔끔한 코드에 AutoCloseable 사용:
public static String execCmd(String cmd) {
String result = null;
try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
result = s.hasNext() ? s.next() : null;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
클래스 경로에서 Apache commons-io를 이미 사용할 수 있는 경우 다음을 사용할 수 있습니다.
Process p = new ProcessBuilder("cat", "/etc/something").start();
String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
이 기사에서 코드를 포함한 다른 모든 답변은 교착 상태를 초래할 수 있습니다.
프로세스의 버퍼는 한정되어 있습니다.stdout
그리고.stderr
산출량.동시에 듣지 않으면 하나를 읽는 동안 둘 중 하나가 채워집니다.예를 들어, 읽기 위해 대기하고 있을 수 있습니다.stdout
기입 대기 중에stderr
에서 읽을 수 없습니다.stdout
버퍼는 비어 있기 때문에 프로세스가 버퍼에 쓸 수 없습니다.stderr
버퍼가 꽉 찼기 때문입니다.당신들은 서로를 영원히 기다리고 있어요.
다음으로 데드록의 위험 없이 프로세스의 출력을 읽을 수 있는 방법을 제시하겠습니다.
public final class Processes
{
private static final String NEWLINE = System.getProperty("line.separator");
/**
* @param command the command to run
* @return the output of the command
* @throws IOException if an I/O error occurs
*/
public static String run(String... command) throws IOException
{
ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true);
Process process = pb.start();
StringBuilder result = new StringBuilder(80);
try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())))
{
while (true)
{
String line = in.readLine();
if (line == null)
break;
result.append(line).append(NEWLINE);
}
}
return result.toString();
}
/**
* Prevent construction.
*/
private Processes()
{
}
}
중요한 것은,ProcessBuilder.redirectErrorStream(true)
리다이렉트 됩니다.stderr
에stdout
개울.이를 통해 단일 스트림을 읽을 수 있습니다.stdout
그리고.stderr
이를 수동으로 구현하려면 두 개의 다른 스레드로 스트림을 소비하여 차단하지 않도록 해야 합니다.
또한 스트림을 사용하여 명령 출력을 얻을 수도 있습니다.
public static void main(String[] args) throws IOException {
Runtime runtime = Runtime.getRuntime();
String[] commands = {"free", "-h"};
Process process = runtime.exec(commands);
BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
lineReader.lines().forEach(System.out::println);
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
errorReader.lines().forEach(System.out::println);
}
@Senthil 및 @Arnd answer(https://stackoverflow.com/a/5711150/2268559) 언급)ProcessBuilder
다음은 를 사용하는 예입니다.ProcessBuilder
다음 명령어에 대해 환경 변수 및 작업 폴더를 지정합니다.
ProcessBuilder pb = new ProcessBuilder("ls", "-a", "-l");
Map<String, String> env = pb.environment();
// If you want clean environment, call env.clear() first
//env.clear();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
File workingFolder = new File("/home/user");
pb.directory(workingFolder);
Process proc = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// Read the output from the command:
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null)
System.out.println(s);
// Read any errors from the attempted command:
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
System.out.println(s);
클래스 만들기:
public class Utils {
public static final String SHEL_EXECUTE_ERROR = "SHEL_EXECUTE_ERROR";
public static String shellExec(String cmdCommand) {
final StringBuilder stringBuilder = new StringBuilder();
try {
final Process process = Runtime.getRuntime().exec(cmdCommand);
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (Exception e) {
return SHEL_EXECUTE_ERROR;
}
return stringBuilder.toString();
}
}
및 용도:
final String shellExec = shellExec("cmd /c ver");
final String versionOS = shellExec.equals(SHEL_EXECUTE_ERROR) ? "empty" : shellExec;
이전 답변에서 수정:
public static String execCmdSync(String cmd, CmdExecResult callback) throws java.io.IOException, InterruptedException {
RLog.i(TAG, "Running command:", cmd);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
//String[] commands = {"system.exe", "-get t"};
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
StringBuffer stdOut = new StringBuffer();
StringBuffer errOut = new StringBuffer();
// Read the output from the command:
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
stdOut.append(s);
}
// Read any errors from the attempted command:
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
errOut.append(s);
}
if (callback == null) {
return stdInput.toString();
}
int exitVal = proc.waitFor();
callback.onComplete(exitVal == 0, exitVal, errOut.toString(), stdOut.toString(), cmd);
return stdInput.toString();
}
public interface CmdExecResult{
void onComplete(boolean success, int exitVal, String error, String output, String originalCmd);
}
이 페이지의 다른 부분과 거의 비슷하지만, 함수에 대해 정리하면 됩니다.
String str=shell_exec("ls -l");
Class 함수:
public String shell_exec(String cmd)
{
String o=null;
try
{
Process p=Runtime.getRuntime().exec(cmd);
BufferedReader b=new BufferedReader(new InputStreamReader(p.getInputStream()));
String r;
while((r=b.readLine())!=null)o+=r;
}catch(Exception e){o="error";}
return o;
}
Kotlin에 글을 쓰는 경우 다음을 사용할 수 있습니다.
val firstProcess = ProcessBuilder("echo","hello world").start()
val firstError = firstProcess.errorStream.readBytes().decodeToString()
val firstResult = firstProcess.inputStream.readBytes().decodeToString()
Process p = Runtime.getRuntime().exec("ping google.com");
p.getInputStream().transferTo(System.out);
p.getErrorStream().transferTo(System.out);
.InputStream
「 」:
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send", argument};
Process proc = rt.exec(commands);
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
스트림에러 스트림)을 .proc.getErrorStream()
러러러러출쇄에 。 할 수 .ProcessBuilder
.
언급URL : https://stackoverflow.com/questions/5711084/java-runtime-getruntime-getting-output-from-executing-a-command-line-program
'programing' 카테고리의 다른 글
Java에서 클래스를 매개 변수로 전달하려면 어떻게 해야 합니까? (0) | 2022.06.19 |
---|---|
1 대 다, 다 대 1 및 다 대 다의 차이점 (0) | 2022.06.19 |
반환 유형이 있는 Java 메서드(return 스테이트먼트 없이 컴파일) (0) | 2022.06.18 |
vue에서 정확히 언제 다시 발생합니까? (0) | 2022.06.18 |
Vuex 상태 내에서 맵 사용 (0) | 2022.06.18 |