JAVA:cmd指令调用
/*
* Copyright (c) 2019, Technology. All Rights Reserved. Technology. CONFIDENTIAL
*/
package com.bylz.qurator.util.Transpiler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/**
* @author Gao.Ning
* @version 1.0
* @since 2019年10月12日
*/
public class ExecuteUtil {
public static void main(String[] args) {
/*执行命令*/
String cmd = "python D:\\qcode\\qrunes\\script.py";
executeCmd(cmd);
}
/**
* 执行cmd指令
* @param cmd 执行指令
*/
public static void executeCmd(String cmd) {
try {
String cmdBin = "cmd /c ";
Process process = Runtime.getRuntime().exec(cmdBin + cmd);
PrintWriter writer = new PrintWriter(process.getOutputStream());
CommandThread commandThread = new CommandThread(writer);
commandThread.setName("ExecuteCmdThread");
commandThread.start();
ProcessInputStreamThread inputThread = new ProcessInputStreamThread(process.getInputStream());
ProcessInputStreamThread errorThread = new ProcessInputStreamThread(process.getErrorStream());
inputThread.setName("InputStreamThread");
inputThread.start();
errorThread.setName("ErrorStreamThread");
errorThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
static class CommandThread extends Thread {
PrintWriter writer;
BufferedReader br = null;
CommandThread(PrintWriter writer) {
this.writer = writer;
br = new BufferedReader(new InputStreamReader(System.in));
this.setDaemon(true);
}
@Override
public void run() {
try {
String cmd;
while ((cmd = br.readLine()) != null) {
writer.println(cmd);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != writer) {
writer.close();
}
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
static class ProcessInputStreamThread extends Thread {
InputStream input;
BufferedReader breader = null;
ProcessInputStreamThread(InputStream input) {
this.input = input;
breader = new BufferedReader(new InputStreamReader(input));
}
@Override
public void run() {
try {
String str;
while ((str = breader.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != input) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != breader) {
try {
breader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}