1

My question is how to read file data from a zip, but actually, I have already implemented that part but the issue is I am having different files in zip (all xml) I don't want to parse those file using xml parser anyways I just want to read it, currently my code is reading all the xml files and I am appending all the data in one single String, How can I read and store different files data separately.

My Code-

public class unzipFile {
    public static void main(String[] args) throws IOException {
        String zipFileName = "people.zip";
        StringBuilder s = new StringBuilder();
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
        ZipEntry zipEntry;
        int read;
        while ((zipEntry = zis.getNextEntry())!= null) {
            while ((read = zis.read(buffer, 0, 1024)) >= 0) {
                s.append(new String(buffer, 0, read));
            }
        }
        while (zipEntry != null){
            zipEntry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
        System.out.println("Unzip complete");
        System.out.println("S = "+s);
    } 

It will print all the data in one go from all the files, what should I need to change in order to read data of different files separately ? anyone please help me Thanks !

Amara
  • 341
  • 4
  • 19
  • You are appending read data to `StringBuilder` `s` in while loop. What do you want to do with this? – Orifjon Aug 19 '21 at 06:26
  • Just create a new `StringBuilder` for each `ZipEntry` and create a `Collection` for storing all the `StringBuilder`s. – Abra Aug 19 '21 at 06:29
  • @Orifjon I want to print all the data from all the files, in s I am appending all the data and printing it, but I want to hold data of different files inside different variables instead of appending it to one StringBuffer I don't know how to do that. – Amara Aug 19 '21 at 09:30
  • @Amara., You can create new `StringBuilder` in a loop and add it to a Collection as @Abra mentioned. – Orifjon Aug 19 '21 at 14:15

1 Answers1

1

This prints all files to out. You can change while block to fit your actual needs.

public class unzipFile {
public static void main(String[] args) throws IOException {
    String zipFileName = "people.zip";
    StringBuilder s = new StringBuilder();
    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
    ZipEntry zipEntry;
    int read;
    while ((zipEntry = zis.getNextEntry())!= null) {
        System.out.println("File = "+zipEntry.getName());
        while ((read = zis.read(buffer, 0, 1024)) >= 0) {
            s.append(new String(buffer, 0, read));
        }
        System.out.println("S = "+s);
        s.clear();
    }

    zis.closeEntry();
    zis.close();
    System.out.println("Unzip complete");

} 
Orifjon
  • 915
  • 8
  • 25