简体   繁体   中英

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!

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)

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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