0

我有一个迷你服务器

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()));

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

4

1 回答 1

2
new String(content).getBytes()

是往返 abyte[]到 aString到 a byte[]

您正在使用 JVM 的默认字符集将 转换byte[]为 a 。String如果byte[]包含根据该字符集无效的字节序列,则这些字节无法准确转换为,因此它们将被转换为...您在;char中不期望的东西 String因此当您转换回byte[].

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

于 2018-09-05T21:56:01.557 回答