i want to convert the content to utf-8 charset before i return the string in following method:
public static String getContentResult(URL url) throws IOException{
InputStream in = url.openStream();
StringBuilder sb = new StringBuilder();
byte [] buffer = new byte[4096];
while(true){
int byteRead = in.read(buffer);
if(byteRead == -1)
break;
for(int i = 0; i < byteRead; i++){
sb.append((char)buffer[i]);
}
}
in.close();
return sb.toString();
}
How can i do that?
Thanks!
You don’t want to convert to UTF-8. You want (I believe) to interpret the incoming stream of data as UTF-8.
Options:
Create an
InputStreamReaderwrapping your incoming stream, specifying UTF-8, and read blocks of characters at a time, appending to aStringBuilderUse Guava to read the whole data as a byte array, then convert it in one go:
In either case, you should use a
finallyblock to close the stream, so that you close it even if an exception is thrown.