Java.Util.Zip - Recreating Directory Structure

java.util.zip - Recreating directory structure

The URI class is useful for working with relative paths.

File mydir = new File("C:\\mydir");
File myfile = new File("C:\\mydir\\path\\myfile.txt");
System.out.println(mydir.toURI().relativize(myfile.toURI()).getPath());

The above code will emit the string path/myfile.txt.

For completeness, here is a zip method for archiving a directory:

  public static void zip(File directory, File zipfile) throws IOException {
URI base = directory.toURI();
Deque<File> queue = new LinkedList<File>();
queue.push(directory);
OutputStream out = new FileOutputStream(zipfile);
Closeable res = out;
try {
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
while (!queue.isEmpty()) {
directory = queue.pop();
for (File kid : directory.listFiles()) {
String name = base.relativize(kid.toURI()).getPath();
if (kid.isDirectory()) {
queue.push(kid);
name = name.endsWith("/") ? name : name + "/";
zout.putNextEntry(new ZipEntry(name));
} else {
zout.putNextEntry(new ZipEntry(name));
copy(kid, zout);
zout.closeEntry();
}
}
}
} finally {
res.close();
}
}

This code makes doesn't preserve dates and I'm not sure how it would react to stuff like symlinks. No attempt is made to add directory entries, so empty directories would not be included.

The corresponding unzip command:

  public static void unzip(File zipfile, File directory) throws IOException {
ZipFile zfile = new ZipFile(zipfile);
Enumeration<? extends ZipEntry> entries = zfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File file = new File(directory, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
InputStream in = zfile.getInputStream(entry);
try {
copy(in, file);
} finally {
in.close();
}
}
}
}

Utility methods on which they rely:

  private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
if (readCount < 0) {
break;
}
out.write(buffer, 0, readCount);
}
}

private static void copy(File file, OutputStream out) throws IOException {
InputStream in = new FileInputStream(file);
try {
copy(in, out);
} finally {
in.close();
}
}

private static void copy(InputStream in, File file) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
copy(in, out);
} finally {
out.close();
}
}

The buffer size is entirely arbitrary.

Recreate directory structure when extracting from zip file

Here is some solution: How should I extract compressed folders in java?

Recreating a folder structure inside a Zip file with Java - Empty folders

Java NIO makes this as easy as working with a normal file system.

public static void main(String[] args) throws Exception {
Path zipfile = Paths.get("C:\\Users\\me.user\\Downloads\\myfile.zip");

try (FileSystem zipfs = FileSystems.newFileSystem(zipfile, null);) {
Path extFile = Paths.get("C:\\Users\\me.user\\Downloads\\countries.csv"); // from normal file system
Path directory = zipfs.getPath("/some/directory"); // from zip file system
Files.createDirectories(directory);
Files.copy(extFile, directory.resolve("zippedFile.csv"));
}
}

Given a myfile.zip file in the given directory, the newFileSystem call will detect the file type (.zip mostly gives it away in this case) and create a ZipFileSystem. Then you can just create paths (directories or files) in the zip file system and use the Java NIO Files api to create and copy files.

The above will create the directory structure /some/directory at the root of the zip file and that directory will contain the zipped file.

Recreate Directory Structure and extract Files From byte array of a zip file in Java

Ok, I succeeded with download the file of your above link programmatically:

        List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
ResponseEntity<byte[]> result = restTemplate.exchange( "someurl deleted On purpose",
HttpMethod.GET,
httpEntity,
byte[].class );

ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(result.getBody()));
ZipEntry entry = null;
while ((entry = zipStream.getNextEntry()) != null)
{
System.out.println( "entry: " + entry );
}

The output is:

entry: bridge2cart/
entry: bridge2cart/config.php
entry: bridge2cart/bridge.php
entry: readme.txt

So you might not request the correct media type, or the URL is not correctly encoded.

zip a folder structure using java

write two methods. The first one takes dirpath, makes a zip stream and calls another method which copies files to the zip stream and calls itself recursively for directories as below:

  1. open an entry in the zip stream for the given directory
  2. list files and dirs in the given directory, loop through them
  3. if an entry is a file, open an entry, copy file content to the entry, close it
  4. if an entry is a directory, call this method. Pass the zip stream
  5. close the entry.

The first method closes the zip stream.

How to zip/upzip a folder and all of its files and subdirectories using Java?

The zip entry needs to specify the path of the file inside the archive. You can't add a folder to a zip archive - you can only add the files within the folder.

The naming convention is to use forward slashes as the path separator. If you are zipping a folder with the following files/subdirectories:

c:\foo\bar\a.txt
c:\foo\bar\sub1\b.txt
c:\foo\bar\sub2\c.txt

the zip entry names would be:

a.txt
sub1/b.txt
sub2/c.txt

So to fix your algorithm, add isDirectory() inside your for loop, and then recursively add the files in any subdirectory to the zip. Probably the best way to do this is to have a method:

addDirectoryToZip(String prefix, File directory, ZipOutputStream out)

Here's a solution for the problem: java.util.zip - Recreating directory structure



Related Topics



Leave a reply



Submit