Easy question
How do I read the entire contents of a java.io.InputStream into a string? I have this so far, but it doesn't work (returns null):
byte[] bytesBuffer = null;
String soFar = "";
int currentChar;
int charsReadCount;
try
{
InputStream in = connection.getInputStream();
charsReadCount = in.read(bytesBuffer);
while (charsReadCount > 0) // While there are still some chars
{
soFar += bytesBuffer;
System.out.println("bytesBuffer: \"" + bytesBuffer + "\"");
in.read(bytesBuffer);
}
return soFar;
}
catch (IOException e)
{
System.out.println("IOException while reading from server:");
e.printStackTrace();
return null;
}
[762 byte] By [
filburt1] at [2007-9-26 1:52:15]

You're passing a null reference to the read method. You need to have the reference bytesBuffer point to an array of bytes, then the read method will have someplace to put the bytes:
byte[] bytesBuffer = new byte[2048];
At least I'm not getting an error anymore. But now the read method constantly returns -1 indicating the end of the stream.BTW, the InputStream was created from a java.net.Socket connection after successfully connecting and sending an HTTP request to www.google.com.
You could call Thread.sleep(2000) to delay for 2 seconds, but a better idea might be to read the data in a separate thread that reads the data and times out if it is not received within a certain time period. We're quickly getting beyond the scope of "New to Java Technology", though...
I've been scanning the JDOM mailing lists recently and there's been lots of posts recently on streaming HTTP.
The FAQ gives the following code.
byte[] buf = new byte[length];
new DataInputStream(inputStream).readFully(buf);
InputStream in = new ByteArrayInputStream(buf);
It may well be worth looking through the mailing lists on http://www.jdom.org as I think these may be close to your requirements even if you're not using JDOM.
Rather than trying to read bytes, why not read lines?
You can use a buffered stream to help you out...
java.net.URL url = new URL("http://www.google.com");
String result = new String();
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(url.openStream()));
String inputLine = null;
while ((inputLine = in.readLine()) != null)
{
result+=inputLine;
}
in.close();
System.out.println( "result is : " + result );
--David
>Rather than trying to read bytes, why not read lines?
I'm certainly no expert on this but.....
My understanding is that reading strings across the internet is not safe as it can't be guaranteed that the server you are reading from represents line breaks in the same way as your own.