无法从非空InputStream读取内容
我有一段从非空输入流读取内容的代码。但是,它在 Eclipse 中工作正常,并在我的计算机中使用 ant 脚本,但在另一台计算机上失败,结果是一个空字符串,我检查过,InputStream 不为空。输入流正在读取本地文件,并且该文件不为空。
这是我尝试过的两种不同的方法,它们都返回一个空字符串:
方法 1:
StringBuilder aStringBuilder = new StringBuilder();
String strLine = null;
BufferedReader aBufferedReaders = new BufferedReader(new InputStreamReader(anInputStream, "UTF-8"));
while ((strLine = aBufferedReaders.readLine()) != null)
{
aStringBuilder.append(strLine);
}
return aStringBuilder.toString()
方法 2:
StringBuffer buffer = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = theInputStream.read(b)) != -1;)
{
buffer.append(new String(b, 0, n));
}
String str = buffer.toString();
return str;
提前致谢!
I have a piece of code that reads the content from a non-empty InputStream. However, it works fine in Eclipse and using ant script in my computer, but it fails in an another computer, the result is an empty String, I have checked, the the InputStream is not null. The inputstream is reading a local file, and the file is not empty.
Here are the two different ways I have tried, both of them return an empty String:
Way 1:
StringBuilder aStringBuilder = new StringBuilder();
String strLine = null;
BufferedReader aBufferedReaders = new BufferedReader(new InputStreamReader(anInputStream, "UTF-8"));
while ((strLine = aBufferedReaders.readLine()) != null)
{
aStringBuilder.append(strLine);
}
return aStringBuilder.toString()
Way 2:
StringBuffer buffer = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = theInputStream.read(b)) != -1;)
{
buffer.append(new String(b, 0, n));
}
String str = buffer.toString();
return str;
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
输入流可以为非空,但仍为空 - 如果没有抛出异常但返回空字符串,则输入流为空。您应该首先查看打开输入流的代码 - 从流中读取的代码不是错误的根源,尽管您需要决定要尝试读取的编码并使用它适当地。 (第一个代码对我来说看起来更好,显式使用 UTF-8 并使用
InputStreamReader
进行文本转换。)The input stream can be non-null but still empty - and if no exceptions are being thrown but an empty string is being returned, then the input stream is empty. You should look at the code which is opening the input stream in the first place - the code to read from the stream isn't the source of the error, although you need to decide which encoding you're trying to read, and use that appropriately. (The first code looks better to me, explicitly using UTF-8 and using an
InputStreamReader
for text conversion.)