How to print new line in string casts to ByteBuffer

853 views Asked by At

I am using this piece of code:

String v="bla"; 
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
ByteBuffer updated =encoder.encode(CharBuffer.wrap(v+"albalb"));

The casting works fine, and I succeeded to print this ByteBuffer to a file that located in my cloud. Now, I want a new line after v is printed to the file. I've tried those things:

  • \r\n
  • \n
  • public static String newline = System.getProperty("line.separator");

None of them worked for me. Anyone has idea?

1

There are 1 answers

4
Fred On

The following code seems to work fine for me.

    String v = "Hello"; 
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    ByteBuffer updated =encoder.encode(CharBuffer.wrap(v+"\nWorld!"));
    String s = new String(updated.array(), "UTF-8");
    System.out.println(s);

Maybe the error lies somewhere else?

EDIT with regards to comment.

    //Client side encoding.
    String inputString = "Hello\nWorld!"; 
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] encodedBytes = Base64.getEncoder().encode(inputString.getBytes());
    ByteBuffer updated = encoder.encode(CharBuffer.wrap(new String(encodedBytes, charset)));
    String s = new String(updated.array(), charset);
    System.out.println("Base64 encoded string: " + s);

    //Server side decoding Base64
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer decodedBytes = decoder.decode(updated);
    byte[] decoded = Base64.getDecoder().decode(decodedBytes.toString().getBytes());
    String decodedStr = new String(decoded, charset);
    System.out.println("Base64 decoded string: " + decodedStr);