• java操作linux,调用shell命令


    import org.junit.jupiter.api.Test;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class Test001 {
        public static String exec(String command) throws InterruptedException {
            String returnString = "";
            Process pro = null;
            Runtime runTime = Runtime.getRuntime();
            if (runTime == null) {
                System.err.println("Create runtime false!");
            }
            try {
                pro = runTime.exec(command);
                BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
                PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
                String line;
                while ((line = input.readLine()) != null) {
                    returnString = returnString + line + "
    ";
                }
                input.close();
                output.close();
                pro.destroy();
            } catch (IOException ex) {
                Logger.getLogger(Test001.class.getName()).log(Level.SEVERE, null, ex);
            }
            return returnString;
        }
    
        @Test
        public void test() throws Exception {
            System.out.println(exec("ls -al"));
        }
    
    }

    mac同样适用

    调用shell脚本,判断是否正常执行,如果正常结束,Process的waitFor()方法返回0

    public static void callShell(String shellString) {  
        try {  
            Process process = Runtime.getRuntime().exec(shellString);  
            int exitValue = process.waitFor();  
            if (0 != exitValue) {  
                log.error("call shell failed. error code is :" + exitValue);  
            }  
        } catch (Throwable e) {  
            log.error("call shell failed. " + e);  
        }  
    }
    package test.shell;
    
    import java.io.BufferedReader;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class JavaShellUtil {
        //基本路径
        private static final String basePath = "/tmp/";
    
        //记录Shell执行状况的日志文件的位置(绝对路径)
        private static final String executeShellLogFile = basePath + "executeShell.log";
    
        //发送文件到Kondor系统的Shell的文件名(绝对路径)
        private static final String sendKondorShellName = basePath + "sendKondorFile.sh";
    
        public int executeShell(String shellCommand) throws IOException {
            int success = 0;
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bufferedReader = null;
    //格式化日期时间,记录日志时使用  
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
    
            try {
                stringBuffer.append(dateFormat.format(new Date())).append("准备执行Shell命令 ").append(shellCommand).append(" 
    ");
    
                Process pid = null;
                String[] cmd = {"/bin/sh", "-c", shellCommand};
                //执行Shell命令
                pid = Runtime.getRuntime().exec(cmd);
                if (pid != null) {
                    stringBuffer.append("进程号:").append(pid.toString()).append("
    ");
                    //bufferedReader用于读取Shell的输出内容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
                    pid.waitFor();
                } else {
                    stringBuffer.append("没有pid
    ");
                }
                stringBuffer.append(dateFormat.format(new Date())).append("Shell命令执行完毕
    执行结果为:
    ");
                String line = null;
                //读取Shell的输出内容,并添加到stringBuffer中
                while (bufferedReader != null && (line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line).append("
    ");
                }
            } catch (Exception ioe) {
                stringBuffer.append("执行Shell命令时发生异常:
    ").append(ioe.getMessage()).append("
    ");
            } finally {
                if (bufferedReader != null) {
                    OutputStreamWriter outputStreamWriter = null;
                    try {
                        bufferedReader.close();
                        //将Shell的执行情况输出到日志文件中
                        OutputStream outputStream = new FileOutputStream(executeShellLogFile);
                        outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
                        outputStreamWriter.write(stringBuffer.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        outputStreamWriter.close();
                    }
                }
                success = 1;
            }
            return success;
        }
    
    
    }  

    更多资料:

    http://www.cnblogs.com/shihaiming/p/5884859.html

    http://www.jb51.net/article/69930.htm

  • 相关阅读:
    字符序列(characts)
    装载问题(load)
    哈密顿路
    犯罪团伙
    回溯算法
    维修机器人
    旅行计划
    皇后游戏
    运输
    亲身实测可用的java实现wordxlsxpdf文件下载功能
  • 原文地址:https://www.cnblogs.com/chenglc/p/8082381.html
Copyright © 2020-2023  润新知