使用processbuilder的问题

a6b3iqyw  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(393)

我跟你有点问题 ProcessBuilder.start(); .
下面是代码的示例:

List<String> listOfStrings = new ArrayList<String>();
myListOfString.add("zip");
myListOfString.add("-r");
myListOfString.add(destinationPath);
myListOfString.add(newFilePath);

File zipFile = new File(workingDirectory, fileName + ".zip");

ProcessBuilder processBuilder = new ProcessBuilder(listOfStrings);
prcoessBuilder.directory(workingDirectory);
try{
  Process p = processBuilder.start();
  ...
  ...
  ...
``` `workingDirectory` 已使用验证为工作目录 `workingDirectory.isDirectory()` .
问题发生在 `Process p = processBuilder.start();` 抛出ioexception。
下面是stacktrace:

java.io.IOException: Cannot run program "zip" (in directory ""): error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
...
...
...
``` workingDirectory 不指向特定文件(例如: /path/to/ ,不是 /path/to/file.zip )但是,它是一个有效的目录。这可能就是问题所在吗?
由于项目的性质,我不能给出确切的代码,但我无法想象如果它在某个时间崩溃,输入会有多重要 Process p = processBuilder.start(); 然而,这就是为什么我要伸出援手,所以可能是这样。
如果需要澄清,请告诉我。

xvw2m8pv

xvw2m8pv1#

错误消息说java找不到名为 zip 在当前目录或路径中,可以通过以下方式看到:

String systemPath = System.getenv("PATH");
System.out.println("PATH="+systemPath);

修复启动器以包含“zip”的完整路径,或者修复javavm使用的路径以包含包含 zip .

myListOfString.add("/the/path/to/zip");

或者类似的东西(取决于您的外壳/终端)

export PATH=/the/path/to:$PATH

正如@abra所建议的,有更好的方法可以在java内部压缩而不依赖processbuilder,例如:

public static void zip(Path dir, Path zip) throws IOException
{
    Map<String, String> env = Map.of("create", "true");
    try (FileSystem fs = FileSystems.newFileSystem(zip, env))
    {
        // This predicate processed the action because it makes use of BasicFileAttributes
        // Rather than process a forEach stream which has to call Files.isDirectory(path)
        BiPredicate<Path, BasicFileAttributes> foreach = (p,a) -> {
            copy(p,a, fs.getPath("/"+dir.relativize(p)));
            return false;
        };

        Files.find(dir, Integer.MAX_VALUE, foreach).count();
    }
    System.out.println("ZIPPED "+dir +" to "+zip);
}
private static void copy(Path from, BasicFileAttributes a, Path target)
{
    System.out.println("Copy "+(a.isDirectory() ? "DIR " : "FILE")+" => "+target);
    try
    {
        if (a.isDirectory())
            Files.createDirectories(target);
        else if (a.isRegularFile())
            Files.copy(from, target, StandardCopyOption.REPLACE_EXISTING);
    }
    catch (IOException e)
    {
        throw new UncheckedIOException(e);
    }
}

相关问题