Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从ZipFileInputStream读取UTF-8字符串_Java_Utf 8_Compression_Zipinputstream - Fatal编程技术网

Java 从ZipFileInputStream读取UTF-8字符串

Java 从ZipFileInputStream读取UTF-8字符串,java,utf-8,compression,zipinputstream,Java,Utf 8,Compression,Zipinputstream,我正在尝试从zipFile读取UTF-8文件,结果证明这是一个重大挑战 在这里,我将字符串压缩到字节数组中,以保存到我的数据库中 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zo = new ZipOutputStream( bos ); zo.setLevel(9); BufferedWrite

我正在尝试从zipFile读取UTF-8文件,结果证明这是一个重大挑战

在这里,我将字符串压缩到字节数组中,以保存到我的数据库中

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            ZipOutputStream zo = new ZipOutputStream( bos );
            zo.setLevel(9);

            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(bos, Charset.forName("utf-8"))
                );          
            ZipEntry ze = new ZipEntry("data");         
            zo.putNextEntry(ze);
            zo.write( s.getBytes() );

            zo.close();
            writer.close();

            return bos.toByteArray();
我就是这样读回字符串的:

ZipInputStream zis = new ZipInputStream( new ByteArrayInputStream(bytes) );
ZipEntry entry = zis.getNextEntry();
byte[] buffer = new byte[2048];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int size;

while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
    bos.write(buffer, 0, size);
}

BufferedReader  r = new BufferedReader( new InputStreamReader( new ByteArrayInputStream( bos.toByteArray() ), Charset.forName("utf-8") ) );
StringBuilder b = new StringBuilder();
while (r.ready()) {
    b.append( r.readLine() ).append(" ");
}
我在这里得到的字符串丢失了UTF8字符

更新1: 我改变了代码,将原始字符串的字节数组与从zipfile读取的字节数组进行了比较,结果发现它们非常匹配!所以这可能就是我在得到字节后构建字符串的方式

Arrays.equals(已转换,orgi)


首先,
BufferedReader#ready()
不是读取输入的好指标。原因有很多

第二,您正在使用

b.append( r.readLine() ).append(" ");
它总是在每次迭代中添加一个
。由此产生的
字符串
值必然与原始值不同


第三,

你的问题在于写作,假设
s
是一个
字符串,你有:

zo.write( s.getBytes() );
但这将使用默认编码将
s
转换为字节。您需要使用UTF-8进行转换:

zo.write( s.getBytes("utf-8") );
您对原始字节与未压缩字节相同的观察是有意义的,因为原始写入数据是问题的根源

请注意,您声明了
writer
流,但实际上从未将其用于任何用途(在本文中,您也不应该这样做,因为写入它只会将未压缩的字符串数据写入
zipoutpstream
写入的相同流
bos
)。在这里同时尝试几件不同的事情可能会让你感到困惑,你应该摆脱
writer