如何在java程序中运行命令行命令并将控制台的输出复制到文件中?

时间:2014-11-26 11:34:41

标签: java

class cmdln_file {

    public static void main(String[] args) throws IOException {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        try {
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec("cmd /c dir");
            //Process pr = rt.exec("C://apkfiles//new_pro2.apk");

            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

            String line=null;

            while((line=input.readLine()) != null) {
                System.out.println(line);
            }

            int exitVal = pr.waitFor();
            System.out.println("Exited with error code "+exitVal);

        } catch(Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的问题不是很明确,但如果您的代码运行正常,请将cmd /c dir替换为cmd /c dir > test.txt