1

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?

Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412

1 Answers1

4

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;
    }
StormeHawke
  • 5,987
  • 5
  • 45
  • 73
  • Pardon my lack of knowledge of `java`, but after researching this a bit I am not sure how to append the buffer to my string. – Nic Hubbard Aug 27 '13 at 21:35
  • See my edit. From the javadoc on reader.read(char[]): Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. Parameters: cbuf Destination buffer Returns: The number of characters read, or -1 if the end of the stream has been reached Throws: IOException - If an I/O error occurs – StormeHawke Aug 27 '13 at 21:41
  • You could also use `StringBuffer` instead of `String` for better performance, then do a `toString()` when you return – StormeHawke Aug 27 '13 at 21:41