File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes simple array  question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "simple array  question" Watch "simple array  question" New topic

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 = != -1 ;) {
out.append(new String(b, 0, n));
return out.toString();

catch(Exception e) {
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14118

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:
subject: simple array question