1    // Copyright (C) 2003 Adam Megacz <adam@xwt.org> all rights reserved.
2    //
3    // You may modify, copy, and redistribute this code under the terms of
4    // the GNU Library Public License version 2.1, with the exception of
5    // the portion of clause 6a after the semicolon (aka the "obnoxious
6    // relink clause")
7    
8    package org.xwt.util;
9    import java.io.*;
10   
11   public class InputStreamToByteArray {
12   
13       /** scratch space for isToByteArray() */
14       private static byte[] workspace = new byte[16 * 1024];
15   
16       /** Trivial method to completely read an InputStream */
17       public static synchronized byte[] convert(InputStream is) throws IOException {
18           int pos = 0;
19           while (true) {
20               int numread = is.read(workspace, pos, workspace.length - pos);
21               if (numread == -1) break;
22               else if (pos + numread < workspace.length) pos += numread;
23               else {
24                   pos += numread;
25                   byte[] temp = new byte[workspace.length * 2];
26                   System.arraycopy(workspace, 0, temp, 0, workspace.length);
27                   workspace = temp;
28               }
29           }
30           byte[] ret = new byte[pos];
31           System.arraycopy(workspace, 0, ret, 0, pos);
32           return ret;
33       }
34   
35   }
36