Itai Soudry
Itai Soudry

Reputation: 350

Writing a file from byte array into a zip file

I'm trying to write a file name "content" from a byte array into an existing zip file.

I have managed so far to write a text file \ add a specific file into the same zip. What I'm trying to do, is the same thing, only instead of a file, a byte array that represents a file. I'm writing this program so it will be able to run on a server, so I can't create a physical file somewhere and add it to the zip, it all must happen in the memory.

This is my code so far without the "writing byte array to file" part.

public static void test(File zip, byte[] toAdd) throws IOException {

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    Path path = Paths.get(zip.getPath());
    URI uri = URI.create("jar:" + path.toUri());

    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {

        Path nf = fs.getPath("avlxdoc/content");
         try (BufferedWriter writer = Files.newBufferedWriter(nf, StandardOpenOption.CREATE)) {
             //write file from byte[] to the folder
            }


    }
}

(I tried using the BufferedWriter but it didn't seem to work...)

Thanks!

Upvotes: 3

Views: 5811

Answers (2)

Roberto Piva
Roberto Piva

Reputation: 9

You should use a ZipOutputStream to access the zipped file.

ZipOutputStream lets you add an entry to the archive from whatever you want, specifying the name of the entry and the bytes of the content.

Provided you have a variable named theByteArray here is a snippet to add an entry to an zip file:

ZipOutputStream zos =  new ZipOutputStream(/* either the destination file stream or a byte array stream */);
/* optional commands to seek the end of the archive */
zos.putNextEntry(new ZipEntry("filename_into_the_archive"));
zos.write(theByteArray);
zos.closeEntry();
try {
    //close and flush the zip
    zos.finish();
    zos.flush();
    zos.close();
}catch(Exception e){
    //handle exceptions
}

Upvotes: 0

fge
fge

Reputation: 121692

Don't use a BufferedWriter to write binary content! A Writer is made to write text content.

Use that instead:

final Path zip = file.toPath();

final Map<String, ?> env = Collections.emptyMap();
final URI uri = URI.create("jar:" + zip.toUri());

try (
    final FileSystem zipfs = FileSystems.newFileSystem(uri, env);
)  {
    Files.write(zipfs.getPath("into/zip"), buf,
        StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}

(note: APPEND is a guess here; it looks from your question that you want to append if the file already exists; by default the contents will be overwritten)

Upvotes: 2

Related Questions