【问题标题】:Put a file Json (array) into a zip file [Java]将文件 Json(数组)放入 zip 文件 [Java]
【发布时间】:2021-12-30 02:51:33
【问题描述】:

您好,我是 java 新手,我的英语也不好 lmao 我需要将一个文件 json (它是一个数组 json)放在一个文件 zip trought java 中,但我尝试了多种解决方案并且不起作用:(

这是我的代码:

     JSONParser parser = new JSONParser();
     String desktopPath =(System.getProperty("user.home")+"\\"+"Desktop");
        new File(desktopPath+"\\Service Reply").mkdir();
    String definitivePath = (desktopPath +"\\"+"Service Reply"+"\\");
        
    
    Object obj = parser.parse(new FileReader(definitivePath+"daticliente.json"));

        File f = new File(definitivePath+"//"+"test1.zip");
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
        ZipEntry e = new ZipEntry(definitivePath+"daticliente.json");
        out.putNextEntry(e);
        out.closeEntry();
        out.close();

有什么帮助吗? 问候

【问题讨论】:

  • “不起作用”是什么意思?请添加错误消息和预期与实际结果等。
  • 欢迎回复我,代码创建了文件 zip,但没有将我之前创建的文件 json 放入文件 zip 中。

标签: java json zip


【解决方案1】:

您正在创建一个ZipEntry,但您没有添加文件内容,因此生成的文件为空。您必须阅读该文件并将内容添加到 ZipOutputStream 实例。这是一个例子:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileExample {

    public static void main(String[] args) {
        zipFile("README.md");
    }

    private static void zipFile(String filePath) {
        try {
            final var file = new File(filePath);
            final var zipFileName = file.getName().concat(".zip");

            final var fileOutputStream = new FileOutputStream(zipFileName);
            final var zipOutputStream = new ZipOutputStream(fileOutputStream);

            zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

            final var bytes = Files.readAllBytes(Paths.get(filePath));
            zipOutputStream.write(bytes, 0, bytes.length);
            zipOutputStream.closeEntry();
            zipOutputStream.close();

        } catch (final FileNotFoundException ex) {
            System.err.format("The file %s does not exist", filePath);
        } catch (final IOException ex) {
            System.err.println("I/O error: " + ex);
        }
    }

}

【讨论】:

  • 太棒了!工作愉快!
猜你喜欢
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 2018-12-11
  • 1970-01-01
相关资源
最近更新 更多