KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > rmijdbc > RJSerializer


1
2 package org.objectweb.rmijdbc;
3
4 import java.io.*;
5
6 /**
7  * Utilitary class to "serialize" non-serializable objects, like streams.
8  */

9 public class RJSerializer {
10
11   /**
12    * Flush an input stream into a byte array
13    */

14   public static byte[] toByteArray(InputStream is) throws IOException {
15     if(is == null) return null;
16     int numAvail = is.available();
17     byte[] bytes = new byte[numAvail];
18     int readSoFar = 0;
19     while (numAvail > 0) {
20       int actualRead = is.read (bytes, readSoFar, numAvail);
21       readSoFar += actualRead;
22       numAvail = is.available();
23       if (readSoFar+numAvail > bytes.length) {
24         // need to expand the bytes buffer
25
byte[] newBytes = new byte[(readSoFar+numAvail)*2];
26         System.arraycopy (bytes, 0, newBytes, 0, readSoFar);
27         bytes = newBytes;
28       } // if
29
} // while
30
return bytes;
31   }
32
33   /**
34    * Return an input stream to read a byte array content
35    */

36   public static InputStream toInputStream(byte[] buf) throws IOException {
37     if(buf == null) return null;
38     return new ByteArrayInputStream(buf);
39   }
40
41   /**
42    * Flush a Reader into a char array
43    */

44   public static char[] toCharArray(Reader reader) throws IOException {
45     if(reader == null) return null;
46     BufferedReader s = new BufferedReader(reader);
47     CharArrayWriter cw = new CharArrayWriter();
48     char buf[] = new char[256];
49     int br;
50     while((br = s.read(buf)) >= 0){
51       if (br > 0) cw.write(buf, 0, br);
52     }
53     s.close();
54     return cw.toCharArray();
55   }
56
57   /**
58    * Return a Reader to read a char array content
59    */

60   public static Reader toReader(char[] buf) throws IOException {
61     if(buf == null) return null;
62     return new CharArrayReader(buf);
63   }
64 }
65
66
Popular Tags