Skip to content
Advertisement

Put a file Json (array) into a zip file [Java]

Hello I’m new to java and my english is not good as well lmao I need to put a file json (it’s an array json) in a file zip trought java but i tried multiple solution and doesn’t work 🙁

this is my code:

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

any help ? regards

Advertisement

Answer

You are creating a ZipEntry but you are not adding the file content, so your resulting file is empty. You have to read the file and add the contents to the ZipOutputStream instance. Here is an example:

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

}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement