Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes simple array  question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "simple array  question" Watch "simple array  question" New topic
Author

simple array question

Sunny Gibbony
Ranch Hand

Joined: May 14, 2008
Posts: 39
Hello, just wanted to verify how this method works.

Is the size array 'byte' is 4096 slots big?




private String slurp (InputStream in) {
try {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1 ;) {
out.append(new String(b, 0, n));
}
return out.toString();

}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
[edit]Disable smilies CR[/edit]
[ June 15, 2008: Message edited by: Campbell Ritchie ]
Justin Fox
Ranch Hand

Joined: Jan 24, 2006
Posts: 802
I believe so....

0 - 4095

Justin Fox


You down with OOP? Yeah you know me!
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 12929
    
    3

It works like this:

1. Create a new StringBuffer object
2. Create an array of 4096 bytes
3. Loop: Read some data into the byte array, assign the number of bytes read to n, do this until n == -1 (which means the end of the input stream has been reached)
4. Inside the loop: Create a new String object from the bytes read (bytes 0 to n-1 in the array) and append the string to the StringBuffer object
5. After the loop, return the contents of the StringBuffer as a String
6. Exception handling code: If an exception occurs, print the stack trace and return null as the result


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: simple array question
 
Similar Threads
MD5 output?
reading and writing socket problem
byte[] to string - Not working
Setting file extension
How to access byte array web method