首页 > 安全资讯 >

java执行shell命令

17-03-30

java执行shell命令:java怎么执行shell命令呢?希望下面的文章对大家有所帮助。

java执行shell命令:java怎么执行shell命令呢?希望下面的文章对大家有所帮助。
public boolean runCommand(String[] command, String workdirectory) {
    String result = "";
    try 
        ProcessBuilder builder = new ProcessBuilder(command);
        if (workdirectory != null) {
            builder.directory(new File(workdirectory));
        }
        builder.redirectErrorStream(true);
        Process process = builder.start();
        InputStream in = process.getInputStream();
        byte[] buffer = new byte[1024];
        while (in.read(buffer) != -1) {
            String str = new String(buffer);
            result = result + str;
        }
        in.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

for example

public void deleteDirectory(File dir) {
    String[] args = {"/system/bin/rm", "-rf", dir.getPath()};
    runCommand(args, "/system/bin/");
}

2

private List getAllPID(String packageName) {
    Runtime mRuntime = Runtime.getRuntime();
    List list = new ArrayList<>();
    try {
        java.lang.Process mProcess = mRuntime.exec("ps | grep " + packageName);
        BufferedReader mReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream()));
        StringBuffer mRespBuff = new StringBuffer();
        char[] buff = new char[1024];
        int ch = 0;
        while ((ch = mReader.read(buff)) != -1) {
            mRespBuff.append(buff, 0, ch);
        }
        mReader.close();

        String[] all = mRespBuff.toString().split("\n");

        for (String line : all) {
            if (line.contains(packageName)) {
                String[] datas = line.split(" ");
                int index = 0;
                for (int i = 1; i < datas.length; i++) {
                    if (!datas[i].trim().equals("")) {
                        index = i;
                        break;
                    }
                }
                list.add(datas[index]);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}
相关文章
最新文章
热点推荐