[英]How to read a file from a nested zip file using Java NIO
我想從嵌套的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)
你需要第二次使用p(Path)作為參數:
try (FileSystem zipP = FileSystems.newFileSystem(p, null)) {
System.out.println("Success :-)");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.