日期:2014-05-16  浏览次数:20652 次

java里面执行linux命令要注意的地方

???? 先看看一段代码片段。

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {

	class ExeCom extends Thread {
		 InputStream is;
		 ExeCom(InputStream is) {
		  this.is = is;
		 }
		 public void run() {
		  try {
		   InputStreamReader isr = new InputStreamReader(is);
		   BufferedReader br = new BufferedReader(isr);
		   String line = null;
		   while ((line = br.readLine()) != null) {
				System.err.println(line);
		   }
		  } catch (IOException ioe) {
		   ioe.printStackTrace();
		  }
		 }
		}
	public void oper(){
		
		 try {
		String[]   command   =   new   String[]   {"sh",   "-c",   "mv /home/1/*.TXT  /home/2/"};
		Process process=Runtime.getRuntime().exec(command);
		new ExeCom(process.getErrorStream()).start();
		process.waitFor();
		System.out.println(new File("e:/2/").list().length);
		} catch (Exception e) {
			e.printStackTrace();
		}				
	}
	
	public static void main(String[] args){
	Test t=	new Test();
		t.oper();
	}
		
}

说明:

?1. 1目录下面有随便建立的几个空文件,2目录是空的

?2.要将1目录下面所有的文件移动到2目录下面,这里就要设置参数,否则会被认为是*.txt。在dos下面就会这么认为,

?? 如果是linux或者unix系统,要加sh。即便是在window下面,执行很多命令,也要加运行环境,否则报ioexception。

3.一定要用缓冲流,否则可能造成死锁。

?

?4.waitFor方法就是:

causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits

,也就是直到这个命令执行完了,才接着往下执行。

?

参考资料:http://okone96.itpub.net/post/9033/60404

?