java - 如何读取zip文件中的文件?

标签 java file spring-boot zip

请帮忙。我想从 zip 文件中读取文件。我的 zip 文件是 MultipartFile。然后我使用 ZipInputStream 获取其输入文件,但是,它给出了未找到文件的错误。

    public String importProject(MultipartFile file) throws IOException, ParseException {
    //Reading the input of zip file,
    ZipInputStream zin = new ZipInputStream(file.getInputStream());
    ZipEntry ze;
    FileInputStream excel = null;
    ArrayList<AnimationSvg> animationSvgs = new ArrayList<>();
    while ((ze = zin.getNextEntry()) != null) {
        if(ze.getName().contains(".xlsx")){
            excel = new FileInputStream(ze.getName());
        }
        else if(ze.getName().contains(".svg")){
            FileInputStream svg = new FileInputStream(ze.getName());
            AnimationSvg animationSvg = new AnimationSvg();
            animationSvg.setName(ze.getName());
            StringBuilder svgContent = new StringBuilder();
            int i;
            while((i = svg.read())!=-1) {
                svgContent.append(String.valueOf((char) i));
            }
            animationSvg.setSvgContent(String.valueOf(svgContent));
            animationSvgs.add(animationSvg);
        }
        zin.closeEntry();
    }
    zin.close();

最佳答案

zip 存档中的条目不是文件。它只是 zip 中的一系列压缩字节。

根本不要使用 FileInputStream。只需从 ZipInputStream 中读取 zip 条目数据即可:

Path spreadsheetsDir = Files.createTempDirectory(null);
Path excel = null;

while ((ze = zin.getNextEntry()) != null) {
    String name = ze.getName();
    if (name.endsWith(".xlsx")) {
        excel = spreadsheetsDir.resolve(name));
        Files.copy(zin, excel);
    } else if (name.endsWith(".svg")) {
        AnimationSvg animationSvg = new AnimationSvg();
        animationSvg.setName(name);
        animationSvg.setSvgContent(
            new String(zin.readAllBytes(), StandardCharsets.UTF_8));
        animationSvgs.add(animationSvg);
    }
    zin.closeEntry();
}

关于java - 如何读取zip文件中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52880088/

相关文章:

java - 比较对象的属性值,但不比较对象类型

c# - C#从文本文件中读取数字

java - 无法将文件从我的计算机本地目录加载到java程序

java - 如何修复 "com.jdbc.SQLServerException: Invalid column name ' taxi_id' "

java - Robotium - 在 Sleeper 类中自定义暂停持续时间

java - Spring Boot 中的 ComponentScan 流程

java cassandra对象映射注释

perl - 仅当文件尚未打开时,如何才能在 Perl 中打开它?

java - @Bean 方法中的 Http header 字段

java - Spring-Boot 应用程序中未保留时区更改