View Javadoc

1   package com.explosion.utilities;
2   
3   /*
4    * =============================================================================
5    * 
6    * Copyright 2004 Stephen Cowx
7    * 
8    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9    * use this file except in compliance with the License. You may obtain a copy of
10   * the License at
11   * 
12   * http://www.apache.org/licenses/LICENSE-2.0
13   * 
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   * 
20   * =============================================================================
21   */
22  
23  import java.io.BufferedInputStream;
24  import java.io.BufferedOutputStream;
25  import java.io.ByteArrayInputStream;
26  import java.io.ByteArrayOutputStream;
27  import java.io.Externalizable;
28  import java.io.File;
29  import java.io.FileOutputStream;
30  import java.io.IOException;
31  import java.io.InputStream;
32  import java.io.ObjectInputStream;
33  import java.io.ObjectOutputStream;
34  import java.util.StringTokenizer;
35  import java.util.Vector;
36  
37  /***
38   * Title: ByteUtils Description: If youre dealing with bytes and binary data,
39   * this class will be the place to find or put your util methods
40   * 
41   * @author Stephen Cowx
42   * @version 1.0
43   */
44  public class ByteUtils
45  {
46  
47      private static final int HEX_37 = 0x37;
48  
49      private static final int HEX_F0 = 0xF0;
50  
51      private static final char CHAR_0 = '0';
52  
53      private static final int HEX_9 = 0x9;
54  
55      private static final int HEX_0F = 0x0F;
56  
57      private static final int HEX_POSITIVE = 0xC;
58  
59      /***
60       * This method returns a char array which represent the given byte array
61       * with characters eg: binary array
62       * [0xFF,0x2C,0x44,0xDA,0x12,0x33,0x54,0xA3] will be represented by the char
63       * array [F,F,2,C,4,4,D,A,1,2,3,3,5,4,A,3]
64       *  
65       */
66      public static char[] getCharsFromBCD(byte[] bytes, boolean replaceFF, boolean ignoreC) throws Exception, IOException
67      {
68          /* Left shifting by two is the same as dividing by two ! */
69          char[] returnChars = new char[bytes.length << 1];
70  
71          for (int i = 0; i < bytes.length; i++)
72          {
73              char[] chars = getCharsFromBCDInt(bytes[i], ignoreC);
74  
75              if (chars[0] == 'F' && replaceFF == true)
76                  chars[0] = ' ';
77  
78              if (chars[1] == 'F' && replaceFF == true)
79                  chars[1] = ' ';
80  
81              returnChars[(i * 2)] = chars[0];
82              returnChars[(i * 2) + 1] = chars[1];
83          }
84          return returnChars;
85      }
86  
87      /***
88       * This method returns a 2 char char array containing characters
89       * representing the high and low nibbles of this byte.
90       */
91      public static char[] getCharsFromBCDInt(int int1, boolean ignoreC) throws Exception
92      {
93          char[] chars = new char[2];
94          int nibblePart;
95  
96          // Convert the left nibble to ascii
97          nibblePart = ((int1 & HEX_F0) >> 4);
98  
99          if (nibblePart > HEX_9)
100             chars[0] = (char) (nibblePart + HEX_37); // Ascii A..F
101         else
102             chars[0] = (char) (nibblePart + CHAR_0); // Ascii 0..9
103 
104         // Convert the right nibble to ascii
105         nibblePart = (int1 & HEX_0F);
106         if (nibblePart != HEX_POSITIVE)
107         {
108             if (nibblePart > HEX_9)
109                 chars[1] = (char) (nibblePart + HEX_37); // Ascii A..F
110             else
111                 chars[1] = (char) (nibblePart + CHAR_0); // Ascii 0..9
112         } else
113         {
114             if (!ignoreC)
115                 chars[1] = (char) (nibblePart + HEX_37);
116         }
117 
118         return chars;
119     }
120 
121     /***
122      * Reads the inputStream into a byteArray
123      */
124     public static byte[] readStreamIntoByteArray(InputStream is) throws Exception
125     {
126         if (is == null)
127             throw new Exception("Method readStreamIntoByteArray(InputStream is) is unable to read inputStream into byte array because the input stream it has been given is null.");
128 
129         byte[] allBytes;
130         Vector byteArrays = new Vector();
131         int i = is.available();
132         int totalbytes = 0;
133         while (i > 0)
134         {
135             totalbytes += i;
136             byte[] bytes = new byte[i];
137             is.read(bytes);
138             i = is.available();
139             byteArrays.addElement(bytes);
140         }
141         is.close();
142 
143         allBytes = new byte[totalbytes];
144         int pos = 0;
145         for (int t = 0; t < byteArrays.size(); t++)
146         {
147             byte[] src = (byte[]) byteArrays.elementAt(t);
148             System.arraycopy(src, 0, allBytes, pos, src.length);
149             pos += src.length;
150         }
151 
152         return allBytes;
153     }
154 
155     /***
156      * Reads the inputStream into a file. It will not append to the file, it will overwrite.
157      */
158     public static void readBinaryStreamIntoFile(InputStream is, File outFile) throws IOException
159     {
160         if (is == null)
161             throw new IOException("Method reaByteStreamIntoFile(InputStream is) is unable to read inputStream into byte array because the input stream it has been given is null.");
162 
163         if (outFile == null)
164             throw new IOException("Method reaByteStreamIntoFile(InputStream is) is unable to read inputStream into byte array because the file it has been given is null.");
165 
166         BufferedInputStream stream = null;
167         BufferedOutputStream outStream = null;
168         try
169         {
170             stream = new BufferedInputStream(is);
171             outStream = new BufferedOutputStream(new FileOutputStream(outFile, false));
172 
173             int i = stream.read();
174             while (i > 0)
175             {
176                 outStream.write(i);
177                 i = stream.read();
178             }
179 
180         } finally
181         {
182             try
183             {
184                 if (stream != null)
185                     stream.close();
186             } catch (IOException e)
187             {
188                 //ignore this we are only trying to clean it up
189             }
190             try
191             {
192                 if (outStream != null)
193                     outStream.close();
194             } catch (IOException e1)
195             {
196                 //ignore this we are only trying to clean it up
197             }
198         }
199     }
200 
201     /***
202      * This method writes the externalizable object out and creates an int
203      * String from it
204      * 
205      * @deprecated
206      */
207     public static String getObjectAsIntString(Externalizable object) throws Exception
208     {
209         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
210         ObjectOutputStream stream = new ObjectOutputStream(outStream);
211         stream.writeObject(object);
212 
213         byte[] bytes = outStream.toByteArray();
214         StringBuffer buffer = new StringBuffer();
215 
216         for (int i = 0; i < bytes.length; i++)
217         {
218             if (i == bytes.length - 1)
219                 buffer.append(Integer.toString(bytes[i]));
220             else
221                 buffer.append(Integer.toString(bytes[i]) + ",");
222         }
223 
224         stream.close();
225         outStream.close();
226 
227         return buffer.toString();
228     }
229 
230     /***
231      * This method creates an object from an externalized object written to an
232      * int string
233      * 
234      * @deprecated
235      */
236     public static Object getObjectFromIntString(String string) throws Exception
237     {
238         StringTokenizer tokeniser = new StringTokenizer(string, ",");
239 
240         int count = 0;
241         byte[] bytes = new byte[tokeniser.countTokens()];
242         while (tokeniser.hasMoreTokens())
243         {
244             String nextToken = tokeniser.nextToken();
245             bytes[count] = (byte) Integer.parseInt(nextToken);
246             count++;
247         }
248 
249         ByteArrayInputStream inStream = new ByteArrayInputStream(bytes);
250         ObjectInputStream stream = new ObjectInputStream(inStream);
251         Object returnObject = stream.readObject();
252         stream.close();
253         inStream.close();
254 
255         return returnObject;
256     }
257 
258     /***
259      * Outputs byte[] to std out delimited by the : character
260      */
261     public static void outputBytes(byte[] bytes)
262     {
263         for (int i = 0; i < bytes.length; i++)
264         {
265             if (i == bytes.length - 1)
266                 System.out.print(bytes[i]);
267             else
268                 System.out.print(bytes[i] + ":");
269         }
270     }
271 
272     /***
273      * Method replaces all occurrances of the searched for char with the
274      * replacewith char in the Stringbuffer provided
275      * 
276      * @param searchFor
277      * @param replaceWith
278      * @param buffer
279      */
280     public static String replace(char searchFor, char replaceWith, String string)
281     {
282         StringBuffer buffer = new StringBuffer(string);
283         while (1 == 1)
284         {
285             int index = buffer.indexOf(Character.toString(searchFor));
286             if (index > 0)
287             {
288                 buffer.replace(index, index + 1, Character.toString(replaceWith));
289             } else
290                 break;
291         }
292 
293         return buffer.toString();
294     }
295 
296 }