通过java运行cmd命令

时间:2015-08-07 12:42:46

标签: java process cmd exec

我试图通过java执行cmd命令来保存Android设备的logcat,尽管我指定的文件中保存的logcat从未创建过。有人告诉我为什么会这样吗? 我要执行的cmd命令是“adb logcat> C:/Users/user1/Desktop/log1.txt”。 我用来执行它的代码是:

try {
    // create a new array of 4 strings
    String[] cmdArray = new String[4];

    cmdArray[0] = "adb";
    cmdArray[1] = " logcat";
    cmdArray[2] = " >";
    cmdArray[3] = " C:/Users/amantsakov/Desktop/logcat.txt";

    // create a process and execute cmdArray
    Process process = Runtime.getRuntime().exec(cmdArray);

} catch (Exception ex) {
    ex.printStackTrace();
}

1 个答案:

答案 0 :(得分:1)

希望这对你有用

String[] exeCmd = new String[] { "ffmpeg", "-i", "C:\\test\\Veham.mp3",
                "-i", "C:\\test\\test.mp4", "-acodec", "copy", "-vcodec",
                "copy", "C:\\test\\outPut.mp4" };

        ProcessBuilder pb = new ProcessBuilder(exeCmd);
        boolean exeCmdStatus = executeCMD(pb);

        return exeCmdStatus;


private static boolean executeCMD(ProcessBuilder pb) {
        pb.redirectErrorStream(true);
        Process p = null;

        try {
            p = pb.start();

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("oops");
            p.destroy();
            return false;
        }
        // wait until the process is done
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("woopsy");
            p.destroy();
            return false;
        }
        return true;
    }// End function executeCMD

这些方法将有助于从java运行cmd命令。