访问手机版  

Linux常用命令|Linux培训学习|考试认证|工资待遇与招聘,认准超级网工!

招聘|合作 登陆|注册

网络工程师培训

当前位置:网络工程师 > 技术课程 > linux > 热点关注 > linux常用命令

Java调用Linux命令(cd的处理)

时间:2019-07-10

linux 命令_linux重启命令_linux命令

Java调用Linux命令(cd的处理)

一、Java调用Linux系统的命令非常简单

这是一个非常常用的调用方法示例:

 1     public String executeLinuxCmd(String cmd) {
 2         System.out.println("got cmd job : " + cmd);
 3         Runtime run = Runtime.getRuntime();
 4         try {
 5             Process process = run.exec(cmd);
 6             InputStream in = process.getInputStream();
 7             BufferedReader bs = new BufferedReader(new InputStreamReader(in));
 8             // System.out.println("[check] now size \n"+bs.readLine());
         
StringBuffer out = new StringBuffer();
         byte[] b = new byte[8192];
         for (int n; (n = in.read(b)) != -1;) {
           out.append(new String(b, 0, n));
        }
         System.out.println("job result [" + out.toString() + "]");

linux命令_linux 命令_linux重启命令

14             in.close();
15             // process.waitFor();
16             process.destroy();
17             return result;
18         } catch (IOException e) {
19             e.printStackTrace();
20         }
21         return null;
22     }

二、含有管道符(|)多级命令串联查询

public List<String> executeLinuxCmd(String cmd) {
        System.out.println("got cmd job : " + cmd);
        Runtime run = Runtime.getRuntime();
        try {
//            Process process = run.exec(cmd);
            Process process = run.exec(new String[] {"/bin/sh", "-c", cmd});
            InputStream in = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(in));
            List<String> list = new ArrayList<String>();
            String result = null;
            while ((result = bs.readLine()) != null) {
                System.out.println("job result [" + result + "]");
                list.add(result);
            }
            in.close();
            // process.waitFor();
            process.destroy();
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }