NARU
NARU

Reputation: 2829

Unable to read the content from a non-empty InputStream

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!

Upvotes: 0

Views: 1532

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500495

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.)

Upvotes: 2

Related Questions