运行 Mac (Unix) 上的命令使用 Java - 卡住

Run Command on Mac (Unix) using Java - Stuck

我正在尝试 运行 Java 在 Mac 上的 "tar" 命令。我注意到命令卡住了。 Bascally,文件大小没有增长,命令也没有 return。但是,如果我 运行 在较小的 directiry 上,它工作正常。

这是我的代码:

 try
         {
             Runtime rt = Runtime.getRuntime();

             Process process = new ProcessBuilder(new String[]{"tar","-cvzf",compressFileName+" "+all_dirs}).start();

             InputStream stdin2 = process.getInputStream();
             InputStreamReader isr2 = new InputStreamReader(stdin2);
             BufferedReader br2 = new BufferedReader(isr2);
             String line2 = null;
             System.out.println("<OUTPUT>");
             while ( (line2 = br2.readLine()) != null)
                 System.out.println(line2);
             System.out.println("</OUTPUT>");
             int exitVal3 = process.waitFor();
             System.out.println("Process exitValue .....: " + exitVal3);
         } catch (Throwable t)
           {
             t.printStackTrace();
           }

我也试过:

String tile_command="tar -cvzf file.tar.gz dire_to_compress ";
         String[]  tile_command_arr= new String[]{"bash","-c",tile_command};

 try
         {
             Runtime rt = Runtime.getRuntime();

             Process proc2 = rt.exec(tile_command_arr);
             InputStream stdin2 = process.getInputStream();
             InputStreamReader isr2 = new InputStreamReader(stdin2);
             BufferedReader br2 = new BufferedReader(isr2);
             String line2 = null;
             System.out.println("<OUTPUT>");
             while ( (line2 = br2.readLine()) != null)
                 System.out.println(line2);
             System.out.println("</OUTPUT>");
             int exitVal3 = process.waitFor();
             System.out.println("Process exitValue for tiling .....: " + exitVal3);
         } catch (Throwable t)
           {
             t.printStackTrace();
           }
 ProcessBuilder(new String[]{"tar","-cvzf",compressFileName+" "+all_dirs})

特别有问题。

您不能使用 ProcessBuilder 将两个参数与 space 组合在一起并期望底层进程获得两个参数。它会得到一个,就像你 运行 命令

tar -cvzf 'compressFileName all_dirs'

这会让 tar 想知道为什么要创建一个非常时髦的文件名 compressFileName(space)all_dirs,以及您想将其中的内容放在哪里?

你需要更接近

的东西
String[]{"tar", "-cvzf", compressFileName, all_dirs};

或者如果 all_dirs 是多个目录,您需要一次将它们添加到字符串数组中(通过使用字符串的 ArrayList,然后将数组从 ArrayList 中拉出)。