如何发送 Java InputStream 元素的 EOF?
所以我有以下代码打开输入流并成功收集信息:
httpInput = httpConnection.openInputStream();
sb= new StringBuffer();
while (ch != -1)
{
ch = httpInput.read();
sb.append((char)ch);
}
但是,当我尝试在另一种方法中使用相同的字符串(sb.toString())时,我收到一条错误,指出“期望文件结束。”。那么如何将 EOF 字符附加到我的字符串中呢?注意:响应基本上是来自远程服务器的 xml 文档。
因此,当代码到达“解析”行时,它会给出上面的错误:
bis = new ByteArrayInputStream(sb.toString().getBytes()); doc = docBuilder.parse(bis);
我正在为黑莓应用程序编写此代码。
交流电
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您只想将流读入字节数组,请尝试使用 IOUtilities.streamToBytes()
If you just want to read the stream into a byte array then try using IOUtilities.streamToBytes()
这段代码的一个大问题是,您似乎一次读取一个字节,并假设每个字节都是一个字符。这不一定是真的,但碰巧适用于一些简单的编码,如 ASCII。一次读取一个字节也可能非常慢。
我不知道有 EOF 字符这样的东西——通常“EOF”是从 read() 等方法返回的值 -1,但这不是一个字符。
这另一个方法是什么?它到底在期待什么角色——你能找出来吗?然后添加那个?目前尚不清楚你真正想在那里做什么。
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.
最后一次调用
ch = httpInput.read();
会给出值 -1,然后将其附加到 StringBuffersb
中。但是使用此代码read()
告诉您它已到达流的末尾,它不是您应该附加的字符。你可以这样做:
The last call of
ch = httpInput.read();
gives you the value -1, which is then appended to your StringBuffersb
. But with this coderead()
tells you it has reached the end of the stream, it's not a character that you should append.You could do this instead:
也许 XML 解析器中的错误消息“Expecting end of file”与 EOF 字符无关。它可能表明存在一些 XML 语法问题(可能是 XML 解析器在格式良好的 XML 文档结束后遇到了更多字符)
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)