Java中令人困惑的命令行执行

时间:2018-08-02 11:29:55

标签: java command-line cmd apk gradlew

最近,我在Java应用程序中的命令行执行遇到了一些麻烦。当我执行这样的命令时,一切都会顺利进行:

try {
    Process a = Runtime.getRuntime().exec("cmd /c mkdir C:\\Users\\CA_LTD\\TryoutDir");
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

然后创建一个特定目录。但是,当我想做一些更复杂的操作时,效果并不理想。例如,当我想执行为我的应用程序项目创建APK文件的命令时:

try {
    Process a = Runtime.getRuntime().exec("cmd /c C:\\Users\\CA_LTD\\AndroidStudioProjects\\AMBITION gradlew assembleRelease");
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

为什么会这样?正常的一个短语命令进入而另一个不?

2 个答案:

答案 0 :(得分:1)

将自动解析传递给exec方法的字符串,以定义命令的参数。由于您的路径包含空格(并且可能还包含特殊字符),因此应考虑使用ProcessBuilder来构建命令。

此外,ProcessBuilder的构造函数是要执行的命令,但您也可以使用directory方法来更改工作目录。

try {
    String[] cmd = {"cmd", 
                    "/c", 
                    "gradlew", 
                    "assembleRelease"};
    ProcessBuilder pb = new ProcessBuilder(cmd);
    // Change working directory
    pb.directory(new File("C:\\Users\\CA_LTD\\AndroidStudioProjects\\AMBITION"));
    // Run command
    Process p = pb.start();
    // Wait for completion
    int exitValue = p.waitFor();
    // Check exit value
    if (exitValue != 0) {
        // TODO: Define your behaviour when process exits with non-zero exit value

        // Print command output
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream());
        String outLine = null;
        while ( (outLine = reader.readLine()) != null) {
            System.out.println(outLine);
        }

        // Print command error
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream());
        String errLine = null;
        while ( (errLine = reader.readLine()) != null) {
            System.err.println(errLine);
        }

        // Throw exit value exception
        throw new Exception("ERROR: CMD process exited with non-zero value: " + exitValue);
    }
} catch (IOException ioe) {
    ioe.printStackTrace();
}

如果您不想检查命令的退出值(在Windows中,退出值是名为errorlevel的伪环境变量,如here中所述),您可以执行以下操作:< / p>

try {
    String[] cmd = {"cmd", 
                    "/c", 
                    "gradlew", 
                    "assembleRelease"};
    ProcessBuilder pb = new ProcessBuilder(cmd);
    // Change working directory
    pb.directory(new File("C:\\Users\\CA_LTD\\AndroidStudioProjects\\AMBITION"));
    // Run command
    Process p = pb.start();
    // Wait for completion
    p.waitFor();
} catch (IOException ioe) {
    ioe.printStackTrace();
}

答案 1 :(得分:0)

因此,在@ CristianRamon-Cortes发布解决方案之后,我得到了以下输出:

FAILURE: Build failed with an exception.
Starting a Gradle Daemon, 1 incompatible and 1 stopped Daemons could not be reused, use --status for details
NDK is missing a "platforms" directory.
If you are using NDK, verify the ndk.dir is set to a valid NDK directory.  It is currently set to C:\Users\CA_LTD\AppData\Local\Android\Sdk\ndk-bundle.
If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning.

Incremental java compilation is an incubating feature.

BUILD FAILED

Total time: 29.414 secs

* What went wrong:
Task 'assebleRelease' not found in root project 'AMBITION'. Some candidates are: 'assembleRelease'.

* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Exception in thread "main" java.lang.Exception: ERROR: CMD process exited with non-zero value: 1
    at com.example.test.TestingCmd.main(TestingCmd.java:43)

编辑:哎呀,这只不过是关于汇编中的字母“ m” ... 谢谢@ CristianRamon-Cortes !!!