Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert zip file into bytes in Java

Tags:

java

zip

how can I convert a zip file into bytes?

 byte[] ba;
 InputStream is = new ByteArrayInputStream(ba);
 InputStream zis = new ZipInputStream(is);
like image 448
user3278732 Avatar asked Dec 11 '22 04:12

user3278732


2 Answers

You can read a file from disk into a byte[] using

 byte[] ba = java.nio.file.Files.readAllBytes(filePath);

This is available from Java 7.

like image 149
Thilo Avatar answered Dec 13 '22 16:12

Thilo


The basic principle is to feed the InputStream into the OutputStream, for example...

byte bytes[] = null;
try (FileInputStream fis = new FileInputStream(new File("..."))) {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[1024];
        int read = -1;
        while ((read = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, read);
        }
        bytes = baos.toByteArray();
    } 
} catch (IOException exp) {
    exp.printStackTrace();
}
like image 27
MadProgrammer Avatar answered Dec 13 '22 17:12

MadProgrammer