]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/load/ByteScooper.java
Version 13, August 2011
[GpsPrune.git] / tim / prune / load / ByteScooper.java
1 package tim.prune.load;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 /**
7  * Class to scoop bytes from an input stream into an array.
8  * The size of the array doesn't have to be known in advance.
9  * This is used for getting images and sound files out of zip
10  * files or from remote URLs.
11  */
12 public class ByteScooper
13 {
14         /** Bucket size in bytes */
15         private static final int BUCKET_SIZE = 5000;
16         /** Amount by which barrel size is increased on demand */
17         private static final int BARREL_SIZE_INCREMENT = 100000;
18
19         /**
20          * Scoop bytes from the given input stream and return the result
21          * @param inIs input stream to scoop bytes from
22          * @return byte array
23          */
24         public static byte[] scoop(InputStream inIs) throws IOException
25         {
26                 byte[] _barrel = new byte[BARREL_SIZE_INCREMENT];
27                 byte[] _bucket = new byte[BUCKET_SIZE];
28                 int numBytesInBarrel = 0;
29                 // read from stream into the bucket
30                 int numBytesRead = inIs.read(_bucket);
31                 while (numBytesRead >= 0)
32                 {
33                         // expand barrel if necessary
34                         if ((numBytesInBarrel + numBytesRead) > _barrel.length)
35                         {
36                                 byte[] newBarrel = new byte[_barrel.length + BARREL_SIZE_INCREMENT];
37                                 System.arraycopy(_barrel, 0, newBarrel, 0, numBytesInBarrel);
38                                 _barrel = newBarrel;
39                         }
40                         // copy from bucket into barrel
41                         System.arraycopy(_bucket, 0, _barrel, numBytesInBarrel, numBytesRead);
42                         numBytesInBarrel += numBytesRead;
43                         // read next lot from stream into the bucket
44                         numBytesRead = inIs.read(_bucket);
45                 }
46                 // Now we know how many bytes there are, so crop to size
47                 if (numBytesInBarrel == 0) return null;
48                 byte[] result = new byte[numBytesInBarrel];
49                 System.arraycopy(_barrel, 0, result, 0, numBytesInBarrel);
50                 return result;
51         }
52 }