Java如何访问压缩文件zip文件中的内容

Java 7的文件系统API允许使用Java NIO文件API读取和添加ZIP文件的条目,以与在任何其他文件系统上运行的方式相同。

文件系统是在使用后应该正确关闭的资源,因此应该使用试用与资源块。

从zip文件中读取

Path pathToZip = Paths.get("path/to/file.zip");
try(FileSystem zipFs = FileSystems.newFileSystem(pathToZip, null)) {
     Path root = zipFs.getPath("/");
     … //access the content of the zip file same as ordinary files
    } catch(IOException ex) {
         ex.printStackTrace();
    }

创建一个新zip文件

Map env = new HashMap<>();
env.put("create", "true"); //required for creating a new zip file
env.put("encoding", "UTF-8"); //optional: default is UTF-8
URI uri = URI.create("jar:file:/path/to/file.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
    Path newFile = zipFs.getPath("/newFile.txt");
    //writing to file
    Files.write(newFile, "Hello world".getBytes());
} catch(IOException ex) {
    ex.printStackTrace();
}
日期:2020-06-02 22:15:22 来源:oir作者:oir