我正在尝试使用java.nio-API遍历.zip文件,但在尝试调用ProviderNotFoundException
时收到FileSystems.newFileSystem
。
我也尝试将zip:file:
更改为jar:file:
,但除了消息显示Provider "jar" not found
之外,我得到了同样的异常。
我还尝试过直接使用FileSystems.newFileSystem(Path, null)
,而不首先创建URI
。
输出:
Reading zip-file: /home/pyknic/Downloads/Walking.zip
Exception in thread "main" java.nio.file.ProviderNotFoundException: Provider "zip" not found
at java.base/java.nio.file.FileSystems.newFileSystem(FileSystems.java:364)
at java.base/java.nio.file.FileSystems.newFileSystem(FileSystems.java:293)
at com.github.pyknic.zipfs.Main.main(Main.java:19)
Main.java
package com.github.pyknic.zipfs;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.stream.StreamSupport;
import static java.lang.String.format;
import static java.util.Collections.singletonMap;
public class Main {
public static void main(String... args) {
final Path zipFile = Paths.get(args[0]);
System.out.println("Reading zip-file: " + zipFile);
final URI uri = URI.create("zip:file:" + zipFile.toUri().getPath().replace(" ", "%20"));
try (final FileSystem fs = FileSystems.newFileSystem(uri, singletonMap("create", "true"))) {
final long entriesRead = StreamSupport.stream(fs.getRootDirectories().spliterator(), false)
.flatMap(root -> {
try {
return Files.walk(root);
} catch (final IOException ex) {
throw new RuntimeException(format(
"Error traversing zip file system '%s', root: '%s'.",
zipFile, root), ex);
}
}).mapToLong(file -> {
try {
Files.lines(file).forEachOrdered(System.out::println);
return 1;
} catch (final IOException ex) {
throw new RuntimeException(format(
"Error modifying DAE-file '%s' in zip file system '%s'.",
file, zipFile), ex);
}
}).sum();
System.out.format("A total of %,d entries read.%n", entriesRead);
} catch (final IOException ex) {
throw new RuntimeException(format(
"Error reading zip-file '%s'.", zipFile
), ex);
}
}
}
如何使用Java Nio-API访问zip文件的文件系统?