views:

626

answers:

4

so i have the following code opening an input stream and collecting the information successfully:

             httpInput = httpConnection.openInputStream();               

             sb= new StringBuffer();             

             while (ch != -1) 
             {
                 ch = httpInput.read();
                 sb.append((char)ch);
             }

however, when i try to use that same string (sb.toString()) in another method, i get an error stating "Expecting end of file.". so how do i attach an EOF character to my string? NOTE: the response is basically an xml document coming from a remote server.

so when the code reaches the "parse" line, it gives me the error above:

bis = new ByteArrayInputStream(sb.toString().getBytes()); doc = docBuilder.parse(bis);

i am coding this for a blackberry application.

ac

+1  A: 

The last call of ch = httpInput.read(); gives you the value -1, which is then appended to your StringBuffer sb. But with this code read() tells you it has reached the end of the stream, it's not a character that you should append.

You could do this instead:

ByteArrayOutputStream out = new ByteArrayOutputStream();
while (true) 
{
    ch = httpInput.read();
    if( ch == -1 ) {
        break;
    }
    out.write( ch );
}
String result = out.toString( "utf-8" ); // or whatever charset is used

// or if you only need another InputStream:
ByteArrayInputStream in = new ByteArrayInputStream( out.getBytes() );
tangens
+1  A: 

One big problem with this code is you seem to be reading one byte at a time and assuming each byte is one character. This is not necessarily at all true, but would happen to work for some simple encoding like ASCII. Reading one byte at a time may also be very slow.

I do not know that there is such a thing as an EOF character -- usually "EOF" is the value -1 returned from methods like read(), but that's not a character.

What is this other method? what character exactly is it expecting -- can you find out? then just add that? It's not clear what you're really trying to do there.

Sean Owen
unfortunately, the blackberry api doesn't allow me to read more than 1 byte at a time using the microedition InputStream object. if there is any other input stream object (within the blackberry api) that i can use to read more than a byte at a time, please let me know so i can use it. thanks!
sexitrainer
There is a read(byte[] b, int off, int len) method in InputStream
Marc Novakowski
+1  A: 

Perhaps the error message "Expecting end of file" in XML parser has nothing to do with EOF character. It may indicate some XML syntax problem (may be, XML parser encountered more characters after the end of a well-formed XML document)

axtavt
+2  A: 

If you just want to read the stream into a byte array then try using IOUtilities.streamToBytes()

Marc Novakowski
this worked like a champ !!!! i liked how it condensed the code to 1 line !!! nice. thank you marc !!!!
sexitrainer