4

I have a JSP application that allows the user to upload a ZIP file and then the application will read all the files in the ZIP and store them in a MySQL.

Upon advice I decided to use "Zip File System Provider" to handle the ZIP file:

Path zipPath = Paths.get(zipFile.getSubmittedFileName());//returns the path to the ZIP file
FileSystem fs = FileSystems.newFileSystem(zipPath, null);//creates the file system

I tried to traverse it using:

for (FileStore store: fs.getFileStores()) {
         System.err.println("Store:  " + store.name());
}

However it loops only one time and returns tmp.zipwhich is the entire ZIP. How do I extract the physical image files one by one so I can store them in MySQL.

Seif
  • 566
  • 2
  • 10
  • 21
  • 1
    Start from the root directories of the `FileSystem` instead of the file stores: `for (Path rootDir : fs.getRootDirectories)` – Jesper Aug 11 '16 at 11:06
  • it returns null. How do I access the files themselves, I can already get the directory, it is only one that the user can upload. – Seif Aug 11 '16 at 11:19
  • 3
    Just use [`Files.walk`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption...-) - it is about 1 line of code. You are looping over the underlying _store_, which is of course the zip. You need to look _at the filesystem_. `fs.getPath("/")` for example. – Boris the Spider Aug 11 '16 at 11:24
  • 1
    What returns `null`; does `fs.getRootDirectories()` return `null`? That would be really strange. – Jesper Aug 11 '16 at 11:26
  • As @Jesper says `FileSystem.getRootDirectories()` cannot return `null`. – Boris the Spider Aug 11 '16 at 11:27
  • I used: Files.walk(zipPath).forEach(System.out::println); and it also returns just the ZIP file! how do I break into it? @BoristheSpider – Seif Aug 11 '16 at 11:54
  • @BoristheSpider I reached this stage. is it possible to take a look. http://stackoverflow.com/questions/38919942/i-cant-get-convert-files-i-get-from-zip-file-system-provider-into-inputstream-t – Seif Aug 12 '16 at 14:18
  • @BoristheSpider RTFM is not an appropriate response on Stackoverflow. – java-addict301 Nov 20 '17 at 19:24

2 Answers2

1

Here's code that traverses given ZIP file and prints first 16 bytes of each file inside.

Path filePath = Paths.get("somefile.zip");
FileSystem fileSystem = FileSystems.newFileSystem(filePath, null);
byte[] buffer = new byte[16];
Base64.Encoder encoder = Base64.getEncoder();
for (Path rootDirectory : fileSystem.getRootDirectories()) {
    Files.walk(rootDirectory).forEach(path -> {
        System.out.print(path);
        if (Files.isRegularFile(path)) {
            System.out.print(" ");
            try (InputStream stream = Files.newInputStream(path)) {
                int length = stream.read(buffer);
                for (int i = 0; i < length; i++) {
                    byte b = buffer[i];
                    if (32 <= b && b < 127) {
                        System.out.print((char) b);
                    } else {
                        System.out.printf("\\%02x", b);
                    }
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
        System.out.println();
    });
}
vbezhenar
  • 11,148
  • 9
  • 49
  • 63
-2

The Apache Commons Compress module probably can help you to iterate through the files.

Below is a sample extract that can iterate over multiple files and extract the byte contents Sample

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipTest {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String fileName = "C:\\temp\\ECDS-File-Upload-Processed.zip";
        String destinationDir = "C:\\temp\\mango";
        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(fileName));
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        byte[] buffer = new byte[1024];
        while (zipEntry != null) {
            String zipFileName = zipEntry.getName();
            File extractedFile = new File(destinationDir + File.separator + zipFileName);
            new File(extractedFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(extractedFile);
            int len;
            while ((len = zipInputStream.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            zipEntry = zipInputStream.getNextEntry();
        }
        zipInputStream.closeEntry();
        zipInputStream.close();
    }
}
Saikat
  • 548
  • 1
  • 4
  • 12