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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值