Here is commented and slightly reworked readFully(). It should do
(hopefully) the same thing as the old one but (hopefully again) with a
bit more fluff for the uninitiated like me.

Do you guys think that this method can be put into some sort of
'utility' package? It seems like something generally useful (ie. read a
file into a byte array). Or better still - is there an equivalent
already somewhere in Tomcat?

Bojan
--- 
/home/groups/devel/jakarta/jakarta-tomcat/src/share/org/apache/tomcat/util/depend/DependClassLoader.java
    Mon Sep 17 11:51:16 2001
+++ 
+jakarta-tomcat-changed2/src/share/org/apache/tomcat/util/depend/DependClassLoader.java
+      Wed Sep 19 18:19:21 2001
@@ -263,32 +263,35 @@
         return parent;
     }
 
+    /*
+     * This method reads the supplied InputStream, starting with 1K of data
+     * and then doubles the buffer size when it runs out of space
+     */
     private byte[] readFully( InputStream is )
        throws IOException
     {
-       byte b[]=new byte[1024];
-       int count=0;
-
-       int available=1024;
+       byte b[]=new byte[1024]; // buffer
+       int count=0;             // number of bytes read so far
+       int available=1024;      // free space left in the buffer
+       int nRead;               // number of bytes returned by last read()
        
-       while (true) {
-           int nRead = is.read(b,count,available);
-           if( nRead== -1 ) {
-               // we're done reading
-               byte result[]=new byte[count];
-               System.arraycopy( b, 0, result, 0, count );
-               return result;
-           }
-           // got a chunk
+       while ( (nRead = is.read(b,count,available)) != -1 ) {
+           // got a chunk, fix counters
            count += nRead;
-            available -= nRead;
+           available -= nRead;
            if( available == 0 ) {
-               // buffer full
+               // buffer full, create a new one double its size and swap
                byte b1[]=new byte[ b.length * 2 ];
                available=b.length;
                System.arraycopy( b, 0, b1, 0, b.length );
                b=b1;
            }
         }
+
+       // copy all bytes read into the result array of the correct size
+       byte result[]=new byte[count];
+       System.arraycopy( b, 0, result, 0, count );
+
+       return result;
     }
 }

Reply via email to