简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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