0

I have a mini server

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

Here I get the contents of the files on the server
Next I produce compression and chunking

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;
}

After that, something amazing happens Now in the compressed and chunked content of the file

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

Two of these will print different answers. Why?

  • Why do you think they should print the same? You are doing entirely different things. A good starting point would be the javadoc for the String constructor that you invoke – Erwin Bolwidt Sep 05 '18 at 21:56
  • Possible duplicate of [How to convert byte array to string and vice versa?](https://stackoverflow.com/questions/1536054/how-to-convert-byte-array-to-string-and-vice-versa) – Rob Sep 05 '18 at 21:57
  • @ErwinBolwidt Thank you. But, how i can print the same – JolpNem Sep 12 '18 at 19:39

1 Answers1

2
new String(content).getBytes()

is round-tripping a byte[] to a String to a byte[].

You are converting the byte[] to a String using the JVM's default charset. If the byte[] contains byte sequences which are invalid according to that charset, those bytes can't be accurately converted to char, so they will be converted to... something you don't expect in the String; so they won't be the same as the input when you convert back to byte[].

Don't do this: String is not logically a byte[], it is a char[]. If you want to transmit a byte[] in a String, do something like base64-encoding it first.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243