我想从嵌套的zip文件(另一个zip文件中的一个zip文件)中读取
a.zip-> b.zip-> c.txt
使用Java NIO,但得到一个NullPointerException,为内部zip文件创建FileSystem。
Java NIO支持吗?你有什么暗示我在做什么错吗?
这是测试程序:
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class NestedZipTest
{
public static void main(String[] args)
throws IOException, URISyntaxException
{
Path path = Paths.get("c:\\temp\\a.zip");
System.out.println("Open: " + path.toUri());
try (FileSystem zipfs = FileSystems.newFileSystem(path, null))
{
for (Path rootPath : zipfs.getRootDirectories())
{
Files.walk(rootPath).forEach(p -> {
System.out.println("Root-Path " + rootPath + " File: " + p);
if (p.toString().endsWith(".zip"))
{
System.out.println("Try to open nested zip file " + p);
try
{
URI u = p.toUri();
System.out.println("Nested zip file URI: " + u);
try (FileSystem zipP = FileSystems.newFileSystem(u, null))
{
System.out.println("Success :-)");
}
}
catch (Throwable exp)
{
System.err.println("Creating file system for nested zip file failed :-(");
exp.printStackTrace();
}
}
});
}
}
}
}
输出:
Open: file:///c:/temp/a.zip
Root-Path / File: /
Root-Path / File: /b.zip
Try to open nested zip file /b.zip
Nested zip file URI: jar:file:///c:/temp/a.zip!/b.zip
Creating file system for nested zip file failed :-(
java.lang.NullPointerException
at com.sun.nio.zipfs.ZipFileSystem.<init>(ZipFileSystem.java:103)
at com.sun.nio.zipfs.ZipFileSystemProvider.newFileSystem(ZipFileSystemProvider.java:117)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:326)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:276)
at NestedZipTest.lambda$0(NestedZipTest.java:32)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at NestedZipTest.main(NestedZipTest.java:22)
答案 0 :(得分:0)
您需要第二次使用p(路径)作为参数:
try (FileSystem zipP = FileSystems.newFileSystem(p, null)) {
System.out.println("Success :-)");
}