Friday 25 May 2012

How can I convert byte array to zip file

If you have a zip file on disk, get the size using java.io.File.length(), allocate a byte array "buffer" of that size, open the file with FileInputStream, call read(buffer), close the FileInputStream.

If you have a byte array, open the file with a FileOutputStream, call write(byteArray), close the FileOutputStream.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
byte[] originalContentBytes= new Verification().readBytesFromAFile(new File("E://file.zip"));

private byte[] readBytesFromAFile(File file){
        int start = 0;
        int length = 1024;
        int offset = -1;
        byte[] buffer = new byte[length];
        try{
            //convert the file content into a byte array
            FileInputStream fileInuptStream = new FileInputStream(file);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInuptStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while ((offset = bufferedInputStream.read(buffer, start, length)) != -1) {
                byteArrayOutputStream.write(buffer, start, offset);
            }
            bufferedInputStream.close();
            byteArrayOutputStream.flush();
            buffer = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
        }catch(FileNotFoundException fileNotFoundException){
            fileNotFoundException.printStackTrace();
        }catch(IOException ioException){
            ioException.printStackTrace();
        }
        return buffer;
    }

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...