java调用linux命令行

本文介绍了一个Java程序示例,该程序通过Runtime类执行一系列Linux命令,包括目录切换、文件创建及写入等操作,并展示了如何读取命令执行后的输出。

参考博客:
Java调用Linux命令(cd的处理)

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class CmdTestThree {
    public static void main(String[] args) {
        CmdTestThree cmdTestThree = new CmdTestThree();
        ArrayList<String> cmdList = new ArrayList<>();
//        cmdList.add("firefox");
        cmdList.add("cd /home/dj/test");
        cmdList.add("pwd");
        cmdList.add("touch 1.txt");
        cmdList.add("echo \"Assess\" > 1.txt");
        cmdList.add("touch 2.txt");
        cmdList.add("touch 3.txt");
        List<String> res = cmdTestThree.executeNewFlow(cmdList);
        System.out.println("resaaa:" + res);
    }
    public List<String> executeNewFlow(List<String> commands) {
        List<String> rspList = new ArrayList<String>();
        Runtime run = Runtime.getRuntime();
        try {
            Process proc = run.exec("/bin/bash", null, null);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            for (String line : commands) {
                out.println(line);
            }
            // out.println("cd /home/test");
            // out.println("pwd");
            // out.println("rm -fr /home/proxy.log");
            out.println("exit");// 这个命令必须执行,否则in流不结束。
            String rspLine = "";
            while ((rspLine = in.readLine()) != null) {
                System.out.println(rspLine);
                rspList.add(rspLine);
            }
            proc.waitFor();
            in.close();
            out.close();
            proc.destroy();
        } catch (IOException | InterruptedException e1) {
            e1.printStackTrace();
        }
        return rspList;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值