Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid encoding null (\u0000) when reading from InputStream

I am reading a request body and put it into an input stream. While I am explicitly saying the decode method, I still get many \u0000 (Null) after the string.

InputStream is = exchange.getRequestBody();
byte[] header = new byte[100];
is.read(header);
String s = new String(header, "UTF-8");

How can I avoid this with Standard Java Library? I cannot use third party libraries.

like image 534
FidEliO Avatar asked Dec 19 '12 09:12

FidEliO


People also ask

What is the meaning of u0000 in Java?

The minimum value char can hold is 'u0000' which is a Unicode value denoting 'null' or 0 in decimal. The maximum value it can hold is 'uffff' or 65,535 inclusive. The minimum value which is 'u0000' is also the default value of char.

How do you convert an InputStream into string in Java?

To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.


1 Answers

is.read(header); returns the number of bytes that were actually read. Change your code as

byte[] header = new byte[100];
int n = is.read(header);
String s = new String(header, 0, n, "UTF-8");
like image 140
Evgeniy Dorofeev Avatar answered Sep 18 '22 01:09

Evgeniy Dorofeev