试图从java运行gsutils永远不会返回

时间:2016-09-04 15:23:14

标签: java macos java-8 google-cloud-storage

我尝试在云上从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();
    }
}

但新线程永远不会返回。

坚持到底:

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

有没有办法从谷歌云下载这些文件夹呢?

1 个答案:

答案 0 :(得分:2)

这种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要求您在子流程运行时提供输入或接收输出。