尝试 运行 来自 java 的 gsutils 从不 returns

trying to run gsutils from java never returns

我尝试从 Google 云存储中下载文件夹。

我 运行 来自具有权限的用户的进程(当我 运行 来自 mac 上的常规终端时它有效)

我有这个代码:

public void runCommand() {
    final Process p;
    try {
        p = Runtime.getRuntime().exec(
            "gsutil -m cp -r gs://my_bucket/705/201609040613/output/html_pages file:/Users/eladb/WorkspaceQa/GsClient/build/resources/main/downloads/");

        new Thread(new Runnable() {
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;

            try {
                while ((line = input.readLine()) != null)
                    System.out.println(line);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

但新线程从未returns。

卡在网上:

while ((line = input.readLine()) != null)

还有什么方法可以从 google 云端下载这些文件夹吗?

手动复制 stdout 数据很容易出错(您必须强行关闭流以终止子线程),幸运的是,unnecessary since Java 7:

public void runCommand() {
    try {
        new ProcessBuilder("gsutil", "-m", "cp", "-r",
            "gs://my_bucket/705/201609040613/output/html_pages",
            "file:/Users/eladb/WorkspaceQa/GsClient/build/resources/main/downloads/")
        .inheritIO()
        .start()
        .waitFor();
    } catch(IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

如果您不想以这种方式引导所有三个通道,请参阅redirectOutput(File), redirectOutput(ProcessBuilder.Redirect),以及输入和错误通道的类似方法。


只有(默认)模式ProcessBuilder.Redirect.PIPE要求您在子进程运行时提供输入或接收输出。