1

Welcome,
I have a byte[] which is the binary representation of a String. And I wanted to replace a part of this String and get back the new byte[]!
I have tried:

String string = new String(array);
string = string.replace("#+#","SOME STRING");
array = string.getBytes();

The problem is that array is that the array afterwards is something different and not only because of the replacement.
The content of the array are serialized objects seperated with "#+#".

7
  • what are the array values before and after replace? Commented May 3, 2017 at 15:06
  • 3
    stackoverflow.com/questions/21906002/… Commented May 3, 2017 at 15:06
  • What's the encoding of the serialized file? Commented May 3, 2017 at 15:06
  • ok ok the serialized file is created as normal ObjectOutputStream. Commented May 3, 2017 at 15:07
  • I dont know how it is encoded: FileOutputStream fos = new FileOutputStream(target.getPathAsString()); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(T); oos.close(); fos.close(); Commented May 3, 2017 at 15:08

1 Answer 1

3

Be explicit about the character encoding you are using and use an encoding such as "Latin-1" where all byte sequences map to valid Unicode characters:

String string = new String(array, "Latin-1");
string = string.replace("#+#","SOME STRING");
array = string.getBytes("Latin-1");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.