]> gitweb.fperrin.net Git - GpsPrune.git/blobdiff - src/tim/prune/function/srtm/SrtmSource.java
Read ZIP entries in chunks
[GpsPrune.git] / src / tim / prune / function / srtm / SrtmSource.java
index 5651a3f314656b155e979056ba1deafd0a6cb671..44ceccfab52a13a5ced20108ad539cafbf2c6fb2 100644 (file)
@@ -15,6 +15,29 @@ public abstract class SrtmSource {
        public abstract int getRowSize(SrtmTile inTile);
        protected abstract String getSourceExtension();
 
+       protected int[] slurpTileHeigths(ZipInputStream inStream, int tileSize)
+               throws IOException
+       {
+               int[] heights = new int[tileSize];
+               int dataSize = 2 * tileSize;
+               byte[] buffer = new byte[dataSize];
+               // Read entire file contents into one byte array
+               int alreadyRead = 0;
+               while (alreadyRead < dataSize)
+               {
+                       alreadyRead += inStream.read(buffer, alreadyRead, dataSize - alreadyRead);
+               }
+               for (int i = 0; i < tileSize; i++)
+               {
+                       // Bytes are signed. Cast high-order to int with sign
+                       // extension, and clamp low-order to its unsigned range
+                       heights[i] = buffer[2 * i] * 256 + (0xff & buffer[2 * i + 1]);
+               }
+               // Close stream
+               inStream.close();
+               return heights;
+       }
+
        public int[] getTileHeights(SrtmTile inTile)
                throws SrtmSourceException
        {
@@ -33,16 +56,7 @@ public abstract class SrtmSource {
                        {
                                throw new SrtmSourceException("Tile file "+cacheFileName+" does not have the expected size");
                        }
-                       int[] heights = new int[tileSize];
-                       // Read entire file contents into one byte array
-                       for (int i = 0; i < heights.length; i++)
-                       {
-                               heights[i] = inStream.read() * 256 + inStream.read();
-                               if (heights[i] >= 32768) {heights[i] -= 65536;}
-                       }
-                       // Close stream
-                       inStream.close();
-                       return heights;
+                       return slurpTileHeigths(inStream, tileSize);
                }
                catch (IOException e)
                {
@@ -64,6 +78,8 @@ public abstract class SrtmSource {
 
        public boolean isCached(SrtmTile inTile)
        {
-               return getCacheFileName(inTile).exists();
+               File cachedFileName = getCacheFileName(inTile);
+               return cachedFileName != null &&
+                       getCacheFileName(inTile).exists();
        }
 }