Runtime.getRuntime.exec()不适用于linux命令“tar -xvf filename.tar”

时间:2013-04-11 04:42:48

标签: java unix extract tar

我正在尝试使用Java批处理应用程序解压Unix机器上的文件。

源代码:

String fileName = "x98_dms_12";

Runtime.getRuntime().exec("gunzip "+ fileName + ".tar.gz");
System.out.println(" Gunzip:"+"gunzip "+ fileName + ".tar.gz");

Runtime.getRuntime().exec("tar -xvf "+ fileName + ".tar");
System.out.println(" Extract:tar -xvf "+ fileName + ".tar");

问题描述:

当我运行批处理程序时,它不会(完全)工作。只有gunzip命令有效,将我的fileName.tar.gz转换为fileName.tar。但是untar命令似乎没有做任何事情,并且我的日志或Unix控制台中没有错误或异常。

当我在Unix提示符下运行相同的命令时,它们可以正常工作。

注意:

  1. 执行路径是正确的,因为它将我的* .tar.gz转换为* .tar
  2. 我不能使用“tar -zxvf fileName.tar.gz”,因为属性“z”在我的系统上不起作用。
  3. 没有抛出任何错误或异常。
  4. 请帮忙。

3 个答案:

答案 0 :(得分:2)

有几件事:

  • tar命令将扩展相对于工作目录的文件,可能需要为Java Process对象设置
  • 您应该等待解压过程完成,然后再启动到untar进程
  • 您应该处理来自流程的输出流。

这是一个可以扩展/适应的工作示例。它使用一个单独的类来处理进程输出流:

class StreamGobbler implements Runnable {
    private final Process process;

    public StreamGobbler(final Process process) {
        super();
        this.process = process;
    }

    @Override
    public void run() {
        try {
            final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            reader.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}

public void extractTarball(final File workingDir, final String archiveName)
        throws Exception {
    final String gzFileName = archiveName + ".tar.gz";
    final String tarFileName = archiveName + ".tar";

    final ProcessBuilder builder = new ProcessBuilder();
    builder.redirectErrorStream(true);
    builder.directory(workingDir);
    builder.command("gunzip", gzFileName);
    final Process unzipProcess = builder.start();

    new Thread(new StreamGobbler(unzipProcess)).start();
    if (unzipProcess.waitFor() == 0) {
        System.out.println("Unzip complete, now untarring");

        builder.command("tar", "xvf", tarFileName);
        final Process untarProcess = builder.start();
        new Thread(new StreamGobbler(untarProcess)).start();
        System.out.println("Finished untar process. Exit status "
                + untarProcess.waitFor());
    }
}

答案 1 :(得分:0)

下面的代码将打印执行的命令的输出。检查它是否返回任何错误。

Process p = Runtime.getRuntime().exec("tar -xvf "+ fileName + ".tar");  
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));  
String line = null;  
while ((line = br.readLine()) != null) {  
     System.out.println(line);  
}

答案 2 :(得分:0)

问题是我们提供的命令是UNIX命令,所以它不能在Windows环境中工作。我写了一个脚本文件来克服这个问题,感谢大家的帮助。 Runtime.getRuntime.exec()将花费一些时间来执行给定的命令,因此在每个exec()给thread.wait(3000)完成该过程并转到下一个线程之后。

相关问题