java 执行操作系统命令

  java 执行操作系统命令,包括输出信息的获取和超时判断 

package  com.ctoc.web.msgtools.smtplog;

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

public   class  CommandRunner {
    
private  StringBuilder rsBuilder;
    
private  StringBuilder errBuilder;
    
public   static   final  String LINE_SEPARATOR  =  System.getProperty( " line.separator " );
    
private   long  timeout  =   1000   *   60   *   5 ; // 5分钟
     private  Process p  =   null ;
    
private  String command;


    
public  String runCommand(String command)  throws  CommandException {
        
this .command  =  command;

        
if  (command  ==   null   ||  command.trim().length()  ==   0 ) {
            
throw   new  CommandException( " command is null or empty! " );
        }

        
//  Start up the process
         try  {
            p 
=  Runtime.getRuntime().exec(command);
        } 
catch  (IOException e) {
            e.printStackTrace();
            
throw   new  CommandException(e.getMessage());
        }

        
this .errBuilder  =   new  StringBuilder();
        
this .rsBuilder  =   new  StringBuilder();
        
        Thread tIn  
=     new   CommandOutputStreamReadThread( p.getInputStream(), false );
        Thread tErr  
=     new   CommandOutputStreamReadThread( p.getErrorStream(), true );
        
        
// 超时检查
        Thread tCheck  =   new  TimeOutCheckThread();
        
        tIn.start();
        tErr.start();
        tCheck.start();
        
        
//  Wait for it to finish running
         try  {
            p.waitFor();
            tIn.join();
            tErr.join();
            
            tCheck.stop();
        
        } 
catch  (InterruptedException ie) {

            System.out.println(ie);
        }
        
//  Check the return code

        
//  ok=0;
         int  ret  =  p.exitValue();
        
if (ret  !=   0 ){
            
throw   new  CommandException( " execute fail: "   +  command 
                                        
+ LINE_SEPARATOR  +  
                                        
this .errBuilder.toString());
        }
        
return  rsBuilder.toString();
    }

    
public   void  stopRun(){
        
if (p  !=   null ){
            System.err.println(
" destroy process of command: "   +  command);
            p.destroy();
        }
    }
    
    
/**
     * 命令输出结果获取线程
     * 
@author  qking
     *
     
*/
    
class  CommandOutputStreamReadThread  extends  Thread {
        
private  InputStream is;
        
private   boolean  errorStream;

        CommandOutputStreamReadThread(InputStream is, 
boolean  errorStream) {
            
this .is  =  is;
            
this .errorStream  =  errorStream;
        }

        @Override
        
public   void  run() {
            StringBuilder sb;
            
if (errorStream){
                sb 
=  errBuilder;
            }
else {
                sb 
=  rsBuilder;
            }

            InputStreamReader isr 
=   new  InputStreamReader(is);
            BufferedReader reader 
=   new  BufferedReader(isr);
            String s;
            
try  {
                
while  ((s  =  reader.readLine())  !=   null ) {
                    
if  (s.length()  !=   0 ) {
                        sb.append(s);
                        sb.append(LINE_SEPARATOR);
                        
try  {
                            Thread.sleep(
10 );
                        } 
catch  (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            } 
catch  (IOException ex) {
                ex.printStackTrace();
            }

        }

    }

    
/**
     * 检查操作超时线程
     * 
@author  qking
     *
     
*/
    
class  TimeOutCheckThread  extends  Thread{

        @Override
        
public   void  run() {
            
// -1时不进行超时判断
             if (timeout  ==   - 1 ){
                
return ;
            }
            
try {
                
this .sleep(timeout);
            }
catch (InterruptedException ie){
                ie.printStackTrace();
            }
            
            stopRun();
        }
        
        
    }
    
    
public   static   void  main(String[] args)  throws  Exception {
        CommandRunner cr 
=   new  CommandRunner();

        System.out.println(cr.runCommand(
" test.bat " ));

    }

    
public   long  getTimeout() {
        
return  timeout;
    }

    
public   void  setTimeout( long  timeout) {
        
this .timeout  =  timeout;
    }
}
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以通过调用系统命令的方式操作Linux命令,具体实现可以通过以下代码示例展示。 1. 调用Linux命令执行 ```java import java.io.*; public class LinuxCommand { public static void main(String[] args) { try { Process process = Runtime.getRuntime().exec("ls -al"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 传递参数给Linux命令 ```java import java.io.*; public class LinuxCommand { public static void main(String[] args) { String directory = "/home/user/Documents"; try { Process process = Runtime.getRuntime().exec("ls " + directory); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 3. 在Linux命令中使用管道 ```java import java.io.*; public class LinuxCommand { public static void main(String[] args) { try { Process process = Runtime.getRuntime().exec("ls -al | grep .txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 需要注意的是,通过Java调用Linux命令可能存在安全风险,因此需要谨慎使用。建议使用Java提供的文件操作API来实现文件操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值