Mat*_*att 1 java mount runtime process tar
我目前正在开发一个 Web 应用程序,其中涉及安装驱动器和提取 tar.gz 文件,所有这些都是用 Java 编写的。由于该应用程序在 Linux 环境中运行,我想我应该尝试使用“mount”和“tar”等 unix 命令。
Runtime runtime = Runtime.getRuntime();
Process proc;
String mountCommand = "mount -t cifs -o username=...";
String extractCommand = "tar xzf ..."
proc = runtime.exec(mountCommand);
proc.waitFor();
proc = runtime.exec(extractCommand);
proc.waitFor();
Run Code Online (Sandbox Code Playgroud)
在终端中运行 mount 命令和 extract 命令工作正常,但在 java 中首次运行时失败。第二个 proc.waitFor() 返回退出代码 2。但是,在第一次尝试失败后运行此代码可以正常工作。我有一种感觉,问题是 waitFor() 没有等到挂载命令完全完成。我的代码中是否遗漏了任何重要的内容?
另外,我宁愿用 Java 来完成这一切,但我很难弄清楚如何解压文件,所以我采用了这种方法。(哦,如果有人能告诉我如何做到这一点,我会很高兴)。任何建议将不胜感激!
取得进展。如果有人想知道,以下是我如何用 Java 提取 tar.gz 文件。根据一些在线教程整理而成。
public static void extract(String tgzFile, String outputDirectory)
throws Exception {
// Create the Tar input stream.
FileInputStream fin = new FileInputStream(tgzFile);
GZIPInputStream gin = new GZIPInputStream(fin);
TarInputStream tin = new TarInputStream(gin);
// Create the destination directory.
File outputDir = new File(outputDirectory);
outputDir.mkdir();
// Extract files.
TarEntry tarEntry = tin.getNextEntry();
while (tarEntry != null) {
File destPath = new File(outputDirectory + File.separator + tarEntry.getName());
if (tarEntry.isDirectory()) {
destPath.mkdirs();
} else {
// If the parent directory of a file doesn't exist, create it.
if (!destPath.getParentFile().exists())
destPath.getParentFile().mkdirs();
FileOutputStream fout = new FileOutputStream(destPath);
tin.copyEntryContents(fout);
fout.close();
// Presserve the last modified date of the tar'd files.
destPath.setLastModified(tarEntry.getModTime().getTime());
}
tarEntry = tin.getNextEntry();
}
tin.close();
}
Run Code Online (Sandbox Code Playgroud)