我尝试使用FileSystems.getFileSystem检索磁盘上的压缩文件,但有一个异常:
java.nio.file.FileSystemNotFoundException at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171).这是代码
Path path = Paths.get("/Users/Franz/Documents/plan.zip");
FileSystems.getFileSystem(URI.create("jar:" + path.toUri()));但是如果我创建了一个newFileSystem,在使用getFileSystem之后,它就可以工作了:
Path path = Paths.get("/Users/Franz/Documents/plan.zip");
Map<String, String> env = new HashMap<String, String>();
env.put("create", "false");
URI uri = URI.create("jar:" + path.toUri());
FileSystems.newFileSystem(uri, env);
FileSystem fileSystem = FileSystems.getFileSystem(URI.create("jar:" + path.toUri())); // return ZipFileSystem
Path pathFile = fileSystem2.getPath("plan.docx"); // File in the zip file
Files.exists(pathFile); // returns true;我可以直接使用ZipFileSystem吗?
谢谢。
发布于 2018-02-05 03:28:58
com.sun被认为是专有的,可能会发生变化,所以尽量避免它。取而代之的是,使用像ZipFile这样非常容易理解的东西。如果您将zip文件路径替换为您的文件位置,则下面的代码示例将适用于您。
It is a bad practice to use Sun's proprietary Java classes?
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public static void main(String[] args)
{
try
{
ZipFile zipFile = new ZipFile("path to zip here");
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements())
{
//entry is your individual file within the zip folder
ZipEntry entry = entries.nextElement();
System.out.println(entry.getName());
if( entry.getName().equals("plan.docx") )
{
System.out.println("found file... do some code here");
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}https://stackoverflow.com/questions/48611745
复制相似问题