[英]How to write an array of bytes in zip and then read it from there
Sorry for my English. 对不起我的英语不好。 I need zzat array of bytes (I do it through zip), but I do not use files, channels and buffers.
我需要扎兹字节数组(我通过zip来完成),但是我不使用文件,通道和缓冲区。 After that I need to unload (unzip this array to another array) I did something like this but it doesn't work:
之后,我需要卸载(将该数组解压缩到另一个数组),我做了类似的事情,但是它不起作用:
public class Main {
public static void main(String[] args) {
byte[] b = "Help me please".getBytes();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
baos.write(b);
} catch (IOException e) {
e.printStackTrace();
}
try (ZipOutputStream zos = new ZipOutputStream(baos)){
ZipEntry out = new ZipEntry("1");
zos.putNextEntry(out);
zos.closeEntry();
}
catch (IOException e){
e.printStackTrace();
}
byte[] a = baos.toByteArray(); //compressed array
ByteArrayInputStream bais = new ByteArrayInputStream(a);
try(ZipInputStream zis = new ZipInputStream(bais)){
System.out.println('1');
byte[]c = zis.readAllBytes();
zis.closeEntry();
System.out.println(c.equals(b));
}
catch (IOException e){
e.printStackTrace();
}
}
}
The following worked for me. 以下对我有用。 Note that I open the Zip file stream first, then I open the entry, then I write the bytes.
请注意,我首先打开Zip文件流,然后打开条目,然后写入字节。 It has to go in that order or it doesn't work.
它必须按此顺序执行,否则将无法正常工作。
public class ZipFileTest {
public static void main( String[] args ) throws IOException {
byte[] b = "Help me please".getBytes( "UTF-8" );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try( ZipOutputStream zos = new ZipOutputStream( baos ) ) {
ZipEntry out = new ZipEntry( "1 First" );
zos.putNextEntry( out );
zos.write( b, 0, b.length );
zos.closeEntry();
}
byte[] a = baos.toByteArray(); //compressed array
ByteArrayInputStream bais = new ByteArrayInputStream( a );
try( ZipInputStream zis = new ZipInputStream( bais ) ) {
for( ZipEntry zipe; (zipe = zis.getNextEntry()) != null; ) {
byte[] data = new byte[1024];
int length = zis.read( data, 0, data.length );
System.out.println( "Entry: " + zipe.toString() );
System.out.println( "Data: " + new String( data, 0, length, "UTF-8" ) );
zis.closeEntry();
}
}
}
}
Output: 输出:
run:
Entry: 1 First
Data: Help me please
BUILD SUCCESSFUL (total time: 0 seconds)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.