반응형
Java에서 명령 행 실행
이 질문에는 이미 답변이 있습니다.
Java 응용 프로그램 내에서이 명령 줄을 실행하는 방법이 있습니까?
java -jar map.jar time.rel test.txt debug
명령으로 실행할 수는 있지만 Java에서는 할 수 없습니다.
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
다음과 같이 출력을 볼 수도 있습니다.
final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
Windows에서 실행중인 경우 명령 앞에 "cmd / c"를 넣어야합니다.
표준 출력 및 / 또는 오류에 대해 많은 데이터를 출력 할 경우 호출 된 프로세스가 차단되지 않도록하려면 Craigo에서 제공 한 솔루션을 사용해야합니다. ProcessBuilder가 Runtime.getRuntime (). exec ()보다 낫습니다. 이것은 두 가지 이유 때문입니다. 인수를 더 잘 토큰 화하고 오류 표준 출력도 처리합니다 ( 여기 에서도 확인 ).
ProcessBuilder builder = new ProcessBuilder("cmd", "arg1", ...);
builder.redirectErrorStream(true);
final Process process = builder.start();
// Watch the process
watch(process);
새 함수 "watch"를 사용하여이 데이터를 새 스레드에 수집합니다. 이 스레드는 호출 된 프로세스가 끝나면 호출 프로세스에서 완료됩니다.
private static void watch(final Process process) {
new Thread() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
import java.io.*;
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
더 이상의 문제가 발생하면 다음을 고려하십시오.하지만 위의 내용이 효과가 있다고 생각합니다.
이건 어떤가요
public class CmdExec {
public static Scanner s = null;
public static void main(String[] args) throws InterruptedException, IOException {
s = new Scanner(System.in);
System.out.print("$ ");
String cmd = s.nextLine();
final Process p = Runtime.getRuntime().exec(cmd);
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
}
}
런타임 클래스 내에서 exec 명령을 시도 했습니까?
Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
참고URL : https://stackoverflow.com/questions/8496494/running-command-line-in-java
반응형
'IT박스' 카테고리의 다른 글
현재 구성 변수를 표시하기위한 mysql 명령 (0) | 2020.07.19 |
---|---|
IntelliJ IDEA가 디렉토리를 표시하도록하려면 어떻게합니까? (0) | 2020.07.19 |
PhoneGap : 데스크톱 브라우저에서 실행 중인지 감지 (0) | 2020.07.19 |
기다리는 Thread.Sleep를 얻는 방법? (0) | 2020.07.19 |
제출 버튼없이 Enter 키를 사용하여 양식을 제출 하시겠습니까? (0) | 2020.07.19 |