首页 > 解决方案 > 如何从 zip 中读取不同的 xml 文件

问题描述

我的问题是如何从 zip 中读取文件数据,但实际上,我已经实现了该部分,但问题是我在 zip 中有不同的文件(所有 xml)我不想使用 xml 解析器解析这些文件无论如何我只是想阅读它,目前我的代码正在阅读所有 xml 文件,并且我将所有数据附加到一个字符串中,如何分别读取和存储不同的文件数据。

我的代码-

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);
    } 

它将一次性打印所有文件中的所有数据,我需要更改什么才能分别读取不同文件的数据?任何人请帮助我谢谢!

标签: javaspringspring-bootjava-ee-8

解决方案


这会将所有文件打印到out. 您可以更改while块以适应您的实际需要。

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");

} 

推荐阅读