繁体   English   中英

如何从 zip 文件中读取 XML 文件?

[英]How to read an XML file from a zip file?

是否可以在 Java 中使用 InputStreamReader 读取 XML?

我有一个 zip 文件中的 XML 文件,但我无法读取该文件。 我该怎么做?

我的代码:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class testDenemeZipEXtract {

    public static void main(String[] args) {
        try {
            ZipFile zipFile = new ZipFile("/home/user/Documents/file.zip");
            Enumeration<? extends ZipEntry> entries = zipFile.entries();

            while(entries.hasMoreElements()){
              ZipEntry entry = entries.nextElement();
              InputStream stream = zipFile.getInputStream(entry);

              if(String.valueOf(entry.getName()).contains(".xml")) {
                BufferedReader bf = new BufferedReader(new InputStreamReader(stream));
                while(bf.readLine()!=null){
                  System.out.println(bf.readLine());
                }
              }
            }   
        }catch(Exception e) {}
    }
    
} 

通过运行这个 java 类,我得到了这个响应;

回应图片

此代码不会将 xml 打印为原始文本。 我该怎么做 ?

如果您想要原始输出,您可以将 XML 转换为来自 ZipInputStream 的字符串。

new String(zipInputStream.readAllBytes(), StandardCharsets.UTF_8);

这将返回一个字符串。 但是,它不会在 SAX 文档构建器中正确处理。 这是格式错误的输出。

    // org.apache.commons.io.FileUtils
    String zipSource = "/{user.home}/path/to/file.zip";
    try {
        ZipFile zipFile = new ZipFile(new File(zipSource));
        Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            String filename = FileUtils.basename(zipEntry.getName().toLowerCase(Locale.ROOT));
            if(filename.contains("xccdf") && filename.endsWith("xml")) {
                System.out.println(zipEntry.getName());
                String text = new String(zipFile.getInputStream(zipEntry).readAllBytes(), StandardCharsets.UTF_8);
                System.out.println(text);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM