Unzip to TreeMap in Java

My question is relativistically simple. Does anyone know a free library (LGPL) that is capable of unpacking a zip structure in TreeMap (or a similar iterative structure) for Java?

The point is that I could do it myself, but I don’t want to invent good wheels already :)

Thanks in advance!


So, I want to say that I have a zip file containing several files and directories that can contain more files. What I'm looking for is a convenient way to extract this tree structure into an object graph, whether it be a TreeMap or not. So, for example: a HashMap : {'root' => 'HashMap : {'file1.png' => byte[] content}}

+4
source share
3 answers

So, I want to say that I have a zip file containing several files and directories that can contain more files. What I'm looking for is a convenient way to extract this tree structure into an object graph, whether it be a TreeMap or not. So, for example: HashMap: {'root', 'HashMap: {' file1.png '=> byte [] content}}

As I have answered several times on another question, the Java API does not have a single β€œtree-like” data structure (tree-based interface), since each use requires a different function. For example, your proposed HashMap tree is not implemented in type save mode - you need wrapper objects somewhere.

I don’t know if there is a tree view of the zip file somewhere to (not) answer your question, but creating it is not so difficult as soon as you define the desired tree interface.


So, here is an example class that does what you want (from what I understand).

 import java.io.*; import java.util.*; import java.util.zip.*; /** * A immutable wrapper around {@link ZipEntry} allowing * simple access of the childs of directory entries. */ public class ZipNode { private ZipNode parent; private Map<String,ZipNode> children; private boolean directory; /** * the corresponding Zip entry. If null, this is the root entry. */ private ZipEntry entry; /** the ZipFile from where the nodes came. */ private ZipFile file; private ZipNode(ZipFile f, ZipEntry entry) { this.file = f; this.entry = entry; if(entry == null || entry.isDirectory()) { directory = true; children = new LinkedHashMap<String, ZipNode>(); } else { directory = false; children = Collections.emptyMap(); } } /** * returns the last component of the name of * the entry, ie the file name. If this is a directory node, * the name ends with '/'. If this is the root node, the name * is simply "/". */ public String getName() { if(entry == null) return "/"; String longName = entry.getName(); return longName.substring(longName.lastIndexOf('/', longName.length()-2)+1); } /** * gets the corresponding ZipEntry to this node. * @return {@code null} if this is the root node (which has no * corresponding entry), else the corresponding ZipEntry. */ public ZipEntry getEntry() { return entry; } /** * Gets the ZipFile, from where this ZipNode came. */ public ZipFile getZipFile() { return file; } /** * returns true if this node is a directory node. */ public boolean isDirectory() { return directory; } /** * returns this node parent node (null, if this is the root node). */ public ZipNode getParent() { return parent; } /** * returns an unmodifiable map of the children of this node, * mapping their relative names to the ZipNode objects. * (Names of subdirectories end with '/'.) * The map is empty if this node is not a directory node. */ public Map<String,ZipNode> getChildren() { return Collections.unmodifiableMap(children); } /** * opens an InputStream on this ZipNode. This only works when * this is not a directory node, and only before the corresponding * ZipFile is closed. */ public InputStream openStream() throws IOException { return file.getInputStream(entry); } /** * a string representation of this ZipNode. */ public String toString() { return "ZipNode [" + entry.getName() + "] in [" + file.getName() + "]"; } /** * creates a ZipNode tree from a ZipFile * and returns the root node. * * The nodes' {@link #openStream()} methods are only usable until the * ZipFile is closed, but the structure information remains valid. */ public static ZipNode fromZipFile(ZipFile zf) { return new ZipFileReader(zf).process(); } /** * Helper class for {@link ZipNode#fromZipFile}. * It helps creating a tree of ZipNodes from a ZipFile. */ private static class ZipFileReader { /** * The file to be read. */ private ZipFile file; /** * The nodes collected so far. */ private Map<String, ZipNode> collected; /** * our root node. */ private ZipNode root; /** * creates a new ZipFileReader from a ZipFile. */ ZipFileReader(ZipFile f) { this.file = f; this.collected = new HashMap<String, ZipNode>(); collected.put("", root); root = new ZipNode(f, null); } /** * reads all entries, creates the corresponding Nodes and * returns the root node. */ ZipNode process() { for(Enumeration<? extends ZipEntry> entries = file.entries(); entries.hasMoreElements(); ) { this.addEntry(entries.nextElement()); } return root; } /** * adds an entry to our tree. * * This may create a new ZipNode and then connects * it to its parent node. * @returns the ZipNode corresponding to the entry. */ private ZipNode addEntry(ZipEntry entry) { String name = entry.getName(); ZipNode node = collected.get(name); if(node != null) { // already in the map return node; } node = new ZipNode(file, entry); collected.put(name, node); this.findParent(node); return node; } /** * makes sure that the parent of a * node is in the collected-list as well, and this node is * registered as a child of it. * If necessary, the parent node is first created * and added to the tree. */ private void findParent(ZipNode node) { String nodeName = node.entry.getName(); int slashIndex = nodeName.lastIndexOf('/', nodeName.length()-2); if(slashIndex < 0) { // top-level-node connectParent(root, node, nodeName); return; } String parentName = nodeName.substring(0, slashIndex+1); ZipNode parent = addEntry(file.getEntry(parentName)); connectParent(parent, node, nodeName.substring(slashIndex+1)); } /** * connects a parent node with its child node. */ private void connectParent(ZipNode parent, ZipNode child, String childName) { child.parent = parent; parent.children.put(childName, child); } } // class ZipFileReader /** * test method. Give name of zip file as command line argument. */ public static void main(String[] params) throws IOException { if(params.length < 1) { System.err.println("Invocation: java ZipNode zipFile.zip"); return; } ZipFile file = new ZipFile(params[0]); ZipNode root = ZipNode.fromZipFile(file); file.close(); root.printTree("", " ", ""); } /** * prints a simple tree view of this ZipNode. */ private void printTree(String prefix, String self, String sub) { System.out.println(prefix + self + this.getName()); String subPrefix = prefix + sub; // the prefix strings for the next level. String nextSelf = " β”œβ”€ "; String nextSub = " β”‚ "; Iterator<ZipNode> iterator = this.getChildren().values().iterator(); while(iterator.hasNext()) { ZipNode child = iterator.next(); if(!iterator.hasNext() ) { // last item, without the "|" nextSelf = " ╰─ "; nextSub = " "; } child.printTree(subPrefix, nextSelf, nextSub); } } } 

This has the main method for using the test, its output for one of my jar files:

  / β”œβ”€ META-INF/ β”‚ ╰─ MANIFEST.MF ╰─ de/ ╰─ fencing_game/ β”œβ”€ start/ β”‚ β”œβ”€ Runner.class β”‚ β”œβ”€ ServerMain$1.class β”‚ β”œβ”€ ServerMain.class β”‚ ╰─ package-info.class β”œβ”€ log/ β”‚ β”œβ”€ Log$1.class β”‚ β”œβ”€ Log.class β”‚ β”œβ”€ LogImplClient.class β”‚ β”œβ”€ Loggable.class β”‚ ╰─ package-info.class ╰─ tools/ ╰─ load/ β”œβ”€ ServiceTools$1.class β”œβ”€ ServiceTools$2.class β”œβ”€ ServiceTools$3.class β”œβ”€ ServiceTools.class ╰─ TwoParentClassLoader.class 

(You only need a Unicode-compatible terminal and Unicode encoding for System.out.)

+2
source

What about java.util.zip.ZipFile ? It looks like a pretty trivial wrapper that should do what you want.

0
source

You can use the ZipFile with java.util.ZipFile, get its contents and pass the current content to java.io.File and check if it is Dir, and if so iteration inside it as well, and you can save them in TreeMap, since you go over.

 ZipFile myzip = new ZipFile (new File("pathToMyZipFile.zip")); Enumeration zipEnumerator = myzip.entries(); while(zipEnumerator.hasMoreElements()) { ZipENtry ze= zipEnumerator.nextElement(); if(ze.isDirectory()) { // recurse } else { // add it to treeMap } } 
0
source

Source: https://habr.com/ru/post/1341867/


All Articles