[Webfunds-commits] java/webfunds/util Support.java

Ian Grigg iang@cypherpunks.ai
Sun, 15 Apr 2001 01:29:59 -0400 (AST)


iang        01/04/15 01:29:59

  Modified:    webfunds/util Support.java
  Log:
  added lots of good URL (stream) reading code, that works!  Old stuff
  was junk, did not understand is.available() call.

Revision  Changes    Path
1.3       +40 -6     java/webfunds/util/Support.java

Index: Support.java
===================================================================
RCS file: /home/webfunds/cvsroot/java/webfunds/util/Support.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- Support.java	2001/04/06 15:28:32	1.2
+++ Support.java	2001/04/15 05:29:59	1.3
@@ -1,5 +1,5 @@
 /*
- * $Id: Support.java,v 1.2 2001/04/06 15:28:32 iang Exp $
+ * $Id: Support.java,v 1.3 2001/04/15 05:29:59 iang Exp $
  *
  * Copyright (c) 2000-2001 Systemics Inc on behalf of
  * the WebFunds Development Team.  All Rights Reserved.
@@ -9,6 +9,7 @@
 import java.io.File;
 import java.io.InputStream;
 import java.io.FileInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 
 
@@ -43,14 +44,47 @@
      * Read a file into a byte array
      * @return an array of the contents found at File
      */
-    static byte[] getFile(File file)
+    public static byte[] getFile(File file)
         throws IOException
     {
         FileInputStream fis = new FileInputStream(file);
-        byte[] buf = new byte[fis.available()];
-        fis.read(buf);
-        fis.close();
-        return buf ;
+        // byte[] buf = new byte[fis.available()];
+        // fis.read(buf);
+        // fis.close();
+        return streamToByteArray(fis) ;
     }
 
+    /**
+     * Read a stream into a byte array
+     * @return an array of the contents found in the stream
+     */
+    public static byte[] streamToByteArray(InputStream is)
+        throws IOException
+    {
+        int size = 10240;
+        ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
+        byte[] buf = new byte[size];
+        int offset = 0;
+        while (is.available() >= 0)
+        {
+            int i;
+            i = is.read(buf, offset, size - offset);
+            if (i == -1)                   // EOF!
+               break ;
+            if (i <= 0)
+               throw new IOException("read returned " + i);
+// logmsg("i == " + i + ";  offset == " + offset + "   (" + size + ")");
+            offset += i;
+            if (offset < size)             // partial read?
+                continue ;                 // keep reading until full
+         
+            baos.write(buf);
+            offset = 0;
+        }
+
+        if (offset > 0)
+            baos.write(buf, 0, offset);
+
+        return baos.toByteArray();
+    }
 }