使用 ProcessBuilder 处理通配符

喝着可乐听着歌;敲着代码哼着曲。没有一点点防备,就这样掉进了坑里。下面的代码是用通过ProcessBuilder调用命令来删除以system_开头的文件。 因为之前删除具体文件的时候这个方法非常好用,于是就想当然了。

ArrayList<String> cmd = new ArrayList<String>();

        cmd.add("rm");

        cmd.add("-vrf");

        cmd.add("/tmp/system_*");

        ProcessBuilder pb = new ProcessBuilder(cmd);

        pb.redirectErrorStream(true);

        try {

            Process process = pb.start();

            InputStream is = process.getInputStream();

            BufferedReader read = new BufferedReader(new InputStreamReader(is));

            String line;

            while ((line = read.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

正确的调用是这样的,通配符需要传给bash才能正确处理。

ArrayList<String> cmd = new ArrayList<String>();

        cmd.add("sh");

        cmd.add("-c");

        cmd.add("rm -vrf /tmp/system_*");

        ProcessBuilder pb = new ProcessBuilder(cmd);

        pb.redirectErrorStream(true);

        try {

            Process process = pb.start();

            InputStream is = process.getInputStream();

            BufferedReader read = new BufferedReader(new InputStreamReader(is));

            String line;

            while ((line = read.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }