繁体   English   中英

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

[英]how to run command line commands inside java program and copy the output of console into a file?

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();
        }
    }
}

您的问题不太清楚,但是如果您的代码正常运行,请用cmd /c dir > test.txt替换cmd /c dir

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM