字节与字符串之间的奇怪转换

时间:2018-09-05 21:51:06

标签: java string byte filecontentresult

我有一个小型服务器

byte[] content = fileManager.get(request.getUri());

我在这里获取服务器上文件的内容
接下来,我将进行压缩和分块

content = process(content, response);

private byte[] process(byte[] content, Response response) {
    ProcessorList processors = new ProcessorList();
    processors.add(new CompressDelegator(new GZIPCompressor()));
    processors.add(new ChunkDelegator(new Chunker(30)));
    content = processors.process(content, response);
    return content;
}

此后,发生了一些惊人的事情 现在在文件的压缩和分块内容中

System.out.println(Arrays.toString(content));
System.out.println(Arrays.toString(new String(content).getBytes()));

其中两个将打印不同的答案。为什么?

1 个答案:

答案 0 :(得分:2)

new String(content).getBytes()

正在将byte[]Stringbyte[]来回。

您正在使用JVM的默认字符集将byte[]转换为String。如果byte[]包含根据该字符集无效的字节序列,则无法将这些字节准确地转换为char,因此它们将被转换为... String;因此当您转换回byte[]时,它们将与输入相同。

请勿这样做:String在逻辑上不是byte[],而是(char[]。如果要在byte[]中传输String,请先执行类似base64编码的操作。

相关问题