java runtime.exec()命令不能执行
importjava.io.IOException;publicclassCmd{publicstaticvoidmain(String[]args){try{Runti...
import java.io.IOException; public class Cmd { public static void main(String[] args){ try{ Runtime runtime=Runtime.getRuntime(); String[] cmd={"cmd/c\\","copy"+" ","D:/stock.xml"+" "," D:/backupStock.xml"}; runtime.exec(cmd); }catch (IOException e){ e.getStackTrace(); } } }
展开
1个回答
展开全部
1 Runtime.getRuntime()返回Process对象
2 Process对象拥有输入流和输出流
3 Process对象具有waitFor效应,命令有可能执行不成功!
4 先写入输入流,然后从Process里面读出输出命令即可。
5 以下是比较成功的方法,doc下面的命令几乎都能成功!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
public class Command {
private java.lang.Process p;
private InputStream is;
private OutputStream os;
private BufferedWriter bw;
private BufferedReader br;
private ProcessBuilder pb;
private InputStream stdErr;
public Command() {
}
//获取Process的输入,输出流
public void setCmd(String cmd) {
try {
p = Runtime.getRuntime().exec(cmd);
os = p.getOutputStream();
is = p.getInputStream();
stdErr = p.getErrorStream();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
//向Process输出命令
public void writeCmd(String cmd) {
try {
bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write(cmd);
bw.newLine();
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//读出Process执行的结果
public String readCmd() {
StringBuffer sb = new StringBuffer();
br = new BufferedReader(new InputStreamReader(is));
String buffer = null;
try {
while ((buffer = br.readLine()) != null) {
sb.append(buffer + "\n");
}
System.out.println(p.waitFor());
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
//将命令一股脑塞入list中
public LinkedList<String> doCmd(LinkedList<String> lists) {
LinkedList<String> list = new LinkedList<String>();
for (String s : lists) {
writeCmd(s);
list.add(readCmd());
}
return list;
}
public static void main(String[] args) {
Command cmd = new Command();
cmd.setCmd("cmd");
cmd.writeCmd("copy d:\\stock.xml d:\\backStock.xml");
System.out.println(cmd.readCmd());
//LinkedList<String> list = new LinkedList<String>();
//list.add("dir/b");
//list = cmd.doCmd(list);
// for(String s:list){
// System.out.print(s);
// }
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询