1

我正在尝试使用 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 回答 3

2

有几件事:

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

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

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());
    }
}
于 2013-04-11T06:09:30.527 回答
0

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

于 2013-06-27T06:52:49.937 回答
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);  
}
于 2013-04-11T04:51:16.360 回答