Reputation: 42139
I am working on learning Java
and am going through the examples on the Android website. I am getting remote contents of an XML
file. I am able to get the contents of the file, but then I need to convert the InputStream
into a String
.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
InputStreamReader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
The issue I am having is I don't want the string to be limited by the len
var. But, I don't know java
well enough to know how to change this.
How can I create the char
without a length?
Upvotes: 1
Views: 1596
Reputation: 6207
Generally speaking it's bad practice to not have a max length on input strings like that due to the possibility of running out of available memory to store it.
That said, you could ignore the len
variable and just loop on reader.read(...)
and append the buffer to your string until you've read the entire InputStream
like so:
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
String result = "";
InputStreamReader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
while(reader.read(buffer) >= 0)
{
result = result + (new String(buffer));
buffer = new char[len];
}
return result;
}
Upvotes: 4