对不起,我的英语。 我需要扎兹字节数组(我通过zip来完成),但是我不使用文件,通道和缓冲区。 之后,我需要卸载(将该数组解压缩到另一个数组) 我做了这样的事情,但是不起作用:
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();
}
}
}
答案 0 :(得分:1)
以下内容对我有用。请注意,我先打开Zip文件流,然后打开条目,然后写入字节。它必须按此顺序执行,否则将无法正常工作。
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();
}
}
}
}
输出:
run:
Entry: 1 First
Data: Help me please
BUILD SUCCESSFUL (total time: 0 seconds)