我正在尝试从Mac上的Java运行“tar”命令。我注意到命令卡住了。基本上,文件大小不会增长,命令也不会返回。但是,如果我在较小的方向上运行,它工作正常。
这是我的代码:
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();
}
答案 0 :(得分:2)
ProcessBuilder(new String[]{"tar","-cvzf",compressFileName+" "+all_dirs})
特别成问题。
您不能使用ProcessBuilder将两个参数与空格一起使用,并期望底层进程获得两个参数。它会得到一个,就像你运行命令一样
tar -cvzf 'compressFileName all_dirs'
这会让tar想知道你为什么要创建一个非常时髦的文件名来创建compressFileName(space)all_dirs
,你要把它放在哪里?
你需要更接近的东西
String[]{"tar", "-cvzf", compressFileName, all_dirs};
或如果all_dirs
是多个目录,则需要一次一个地将它们添加到String数组中(通过使用字符串的ArrayList,然后将数组拉出ArrayList)。