gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:07:17 25 4
gpt4 key购买 nike

我正在尝试使用 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. 没有抛出任何错误或异常。

请帮忙。

最佳答案

有几件事:

  • 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());
}
}

关于java - Runtime.getRuntime.exec() 不适用于 linux 命令 "tar -xvf filename.tar",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15940935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com