如何在Java中将zip文件转换为字节

use*_*732 3 java zip

如何将zip文件转换为字节?

 byte[] ba;
 InputStream is = new ByteArrayInputStream(ba);
 InputStream zis = new ZipInputStream(is);
Run Code Online (Sandbox Code Playgroud)

Thi*_*ilo 6

您可以将文件从磁盘读取到byte[]使用中

 byte[] ba = java.nio.file.Files.readAllBytes(filePath);
Run Code Online (Sandbox Code Playgroud)

这可以从Java 7获得.

  • 更新包,byte[] ba = java.nio.file.Files.readAllBytes(file.toPath()); (2认同)

Mad*_*mer 5

其基本原理是喂InputStreamOutputStream,例如...

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();
}
Run Code Online (Sandbox Code Playgroud)