X-Git-Url: https://gitweb.fperrin.net/?p=GpsPrune.git;a=blobdiff_plain;f=src%2Ftim%2Fprune%2Fload%2FByteScooper.java;fp=src%2Ftim%2Fprune%2Fload%2FByteScooper.java;h=facf1c57238857883f1d7d7f7d5c66dca40cf12c;hp=0000000000000000000000000000000000000000;hb=ce6f2161b8596f7018d6a76bff79bc9e571f35fd;hpb=2d8cb72e84d5cc1089ce77baf1e34ea3ea2f8465 diff --git a/src/tim/prune/load/ByteScooper.java b/src/tim/prune/load/ByteScooper.java new file mode 100644 index 0000000..facf1c5 --- /dev/null +++ b/src/tim/prune/load/ByteScooper.java @@ -0,0 +1,52 @@ +package tim.prune.load; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Class to scoop bytes from an input stream into an array. + * The size of the array doesn't have to be known in advance. + * This is used for getting images and sound files out of zip + * files or from remote URLs. + */ +public class ByteScooper +{ + /** Bucket size in bytes */ + private static final int BUCKET_SIZE = 5000; + /** Amount by which barrel size is increased on demand */ + private static final int BARREL_SIZE_INCREMENT = 100000; + + /** + * Scoop bytes from the given input stream and return the result + * @param inIs input stream to scoop bytes from + * @return byte array + */ + public static byte[] scoop(InputStream inIs) throws IOException + { + byte[] _barrel = new byte[BARREL_SIZE_INCREMENT]; + byte[] _bucket = new byte[BUCKET_SIZE]; + int numBytesInBarrel = 0; + // read from stream into the bucket + int numBytesRead = inIs.read(_bucket); + while (numBytesRead >= 0) + { + // expand barrel if necessary + if ((numBytesInBarrel + numBytesRead) > _barrel.length) + { + byte[] newBarrel = new byte[_barrel.length + BARREL_SIZE_INCREMENT]; + System.arraycopy(_barrel, 0, newBarrel, 0, numBytesInBarrel); + _barrel = newBarrel; + } + // copy from bucket into barrel + System.arraycopy(_bucket, 0, _barrel, numBytesInBarrel, numBytesRead); + numBytesInBarrel += numBytesRead; + // read next lot from stream into the bucket + numBytesRead = inIs.read(_bucket); + } + // Now we know how many bytes there are, so crop to size + if (numBytesInBarrel == 0) return null; + byte[] result = new byte[numBytesInBarrel]; + System.arraycopy(_barrel, 0, result, 0, numBytesInBarrel); + return result; + } +}