开发者

How do I send an EOF for a Java InputStream element?

开发者 https://www.devze.com 2022-12-18 20:18 出处:网络
so i have the following code opening an input stream and collecting the information successfully: httpInput = httpConnection.openInputStre开发者_StackOverflow中文版am();

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

             httpInput = httpConnection.openInputStre开发者_StackOverflow中文版am();               

             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


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


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.


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() );


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消