KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gcc > util > JavaObject


1 /*
2  * Copyright 2004 The Apache Software Foundation or its licensors, as
3  * applicable.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14  * implied.
15  *
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */

19 package gcc.util;
20
21 import gcc.*;
22 import java.io.*;
23
24 public abstract class JavaObject
25 {
26     public static byte[] toByteArray(Object object)
27     {
28         if (object == null)
29         {
30             return null;
31         }
32         try
33         {
34             ByteArrayOutputStream bs = new ByteArrayOutputStream();
35             ObjectOutputStream os = new ObjectOutputStream(bs);
36             os.writeObject(object);
37             // Ensure last byte is not NUL. Avoids truncation of values when
38
// stored in Sybase ASE databases.
39
os.writeByte((byte)'.');
40             os.flush();
41             byte[] buffer = bs.toByteArray();
42             os.close();
43             bs.close();
44             return buffer;
45         }
46         catch (Exception ex)
47         {
48             throw new SystemException("JavaObject.toByteArray", ex);
49         }
50     }
51
52     public static java.lang.Object fromByteArray(byte[] buffer)
53     {
54         if (buffer == null)
55         {
56             return null;
57         }
58         try
59         {
60             ByteArrayInputStream bs = new ByteArrayInputStream(buffer);
61             ObjectInputStream is = new ObjectInputStream(bs);
62             Object object = is.readObject();
63             is.close();
64             bs.close();
65             return object;
66         }
67         catch (Exception ex)
68         {
69             throw new SystemException("JavaObject.fromByteArray", ex);
70         }
71     }
72 }
73
Popular Tags