Java/File Input Output/Byte Array

Материал из Java эксперт
Перейти к: навигация, поиск

An implementation of a virtual file, whose contents are kept in memory

   <source lang="java">
     

/**

* The utillib library.
* More information is available at http://www.jinchess.ru/.
* Copyright (C) 2002 Alexander Maryanovsky.
* All rights reserved.
*
* The utillib library is free software; you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* The utillib library is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with utillib library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
*/

import java.io.*;

/**

* An implementation of a virtual file, whose contents are kept in memory.
*/

public class MemoryFile{

 /**
  * The default buffer size.
  */
 private static final int DEFAULT_BUFFER_SIZE = 2048;
 /**
  * The initial buffer size.
  */
 private final int initBufSize;
 /**
  * The data byte array.
  */
 private byte [] data = null;
 /**
  * The amount of bytes that have been written into the file. 
  */
 private volatile int size = 0;
 /**
  * The currently open OutputStream writing into this
  * MemoryFile. null if none.
  */
 private OutputStream out = null;


 /**
  * Creates a new, empty, MemoryFile.
  */
 public MemoryFile(){
   this(null, DEFAULT_BUFFER_SIZE);
 }


 /**
  * Creates a new empty MemoryFile with the specified initial
  * buffer size.
  */
 public MemoryFile(int bufSize){
   this(null, bufSize);
 }


 /**
  * Creates a new MemoryFile initialized with the data from the
  * specified byte array. The specified byte array is copied.
  */
 public MemoryFile(byte [] data){
   this(data, DEFAULT_BUFFER_SIZE);
 }


 /**
  * Creates a new MemoryFile initialized with the data from the
  * specified byte array and the initial buffer size. Note that if the
  * specified initial buffer size is smaller than the length of the byte array,
  * it will only be user when/if the contents of the file are cleared.
  */
 public MemoryFile(byte [] data, int bufSize){
   if (bufSize <= 0)
     throw new IllegalArgumentException("The buffer size must be a positive integer");
   this.initBufSize = bufSize;
   if (data != null){
     this.data = new byte[bufSize > data.length ? bufSize : data.length];
     System.arraycopy(data, 0, this.data, 0, data.length);
     this.size = data.length;
   }
 }


 /**
  * Returns the size of the file.
  */
 public int getSize(){
   return size;
 }
 /**
  * Returns an OutputStream that will write into this
  * MemoryFile. Only a single open OutputStream is
  * allowed per MemoryFile. Note that invoking this method clears
  * the current contents of the file.
  *
  * @throws IOException if an open OutputStream writing into this
  * MemoryFile already exists.
  */
 public synchronized OutputStream getOutputStream() throws IOException{
   if (out != null)
     throw new IOException("MemoryFile already open for writing");
   size = 0;
   data = new byte[initBufSize];
   return out = new InternalOutputStream();
 }


 /**
  * Returns an InputStream that will read from this
  * MemoryFile. Note that the data read from the returned
  * InputStream will be the data in the file when this method is
  * invoked. If more data is written into the file or the contents of the file
  * are cleared, the returned InputStream will not be affected.
  */
 public InputStream getInputStream(){
   return new ByteArrayInputStream(data, 0, getSize());
 }


 /**
  * Clears this file, resetting its size to 0.
  *
  * @throws IOException if the file is currently open for writing.
  */
 public synchronized void clear() throws IOException{
   if (out != null)
     throw new IOException("MemoryFile open for writing");
   size = 0;
 }


 /**
  * Writes the contents of this MemoryFile into the specified
  * OutputStream.
  */
 public synchronized void writeTo(OutputStream out) throws IOException{
   out.write(data, 0, getSize());
 }


 /**
  * Increases the size of the internal buffer by at least the specified amount
  * of bytes. The caller must take care of proper synchronization.
  */
 private void growBuf(int minGrowSize){
   int growSize = minGrowSize < data.length ? data.length : minGrowSize;
   byte [] newData = new byte[data.length + growSize];
   System.arraycopy(data, 0, newData, 0, data.length);
   data = newData;
 }
 /**
  * Writes a single byte into the file.
  */
 private synchronized void write(int b){
   if (data.length - size == 0)
     growBuf(1);
   data[size++] = (byte)(b&0xff);
 }
 /**
  * Writes the specified amount of bytes from the specified array starting with
  * the specified index into the file.
  */
 private synchronized void write(byte [] arr, int offset, int length){
   if (data.length - size < arr.length)
     growBuf(arr.length + size - data.length);
   System.arraycopy(arr, offset, data, size, length);
   size += length;
 }
 /**
  * Closes the OutputStream writing into this file.
  *
  * @throws IOException if the OutputStream is already closed.
  */
 private synchronized void closeOutputStream() throws IOException{
   if (out == null)
     throw new IOException("OutputStream already closed");
   out = null;
 }
 /**
  * The OutputStream class that is responsible for writing into
  * this MemoryFile. This class simply forwards the calls to the
  * methods in its outer class.
  */
 private class InternalOutputStream extends OutputStream{
   public void write(int b){
     MemoryFile.this.write(b);
   }
   public void write(byte [] buf, int offset, int length){
     MemoryFile.this.write(buf, offset, length);
   }
   public void close() throws IOException{
     MemoryFile.this.closeOutputStream();
   }
 }

}




 </source>
   
  
 
  



Byte-Array Conversion Utility Functions

   <source lang="java">
     

import java.io.UnsupportedEncodingException; /**

*

Byte-Array Conversion Utility Functions.

*
* $Id: ByteUtils.java,v 1.6 2005/06/16 19:58:58 mokhov Exp $
*
* @version $Revision: 1.6 $
* @author Serguei Mokhov
* @since 0.3.0
*/

public class ByteUtils {

 /**
  * Allow derivatives.
  */
 protected ByteUtils()
 {
 }
 /**
  * Converts a byte array to short value.
  * Equivalent to byteArrayToShort(paRawBytes, 0, pbBigEndian);
  *
  * @param paRawBytes the byte array
  * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
  *
  * @return short representation of the bytes
  */
 public static short byteArrayToShort(byte[] paRawBytes, boolean pbBigEndian)
 {
   return byteArrayToShort(paRawBytes, 0, pbBigEndian);
 }
 /**
  * Converts a portion of a byte array with given offset to short value.
  *
  * @param paRawBytes the byte array
  * @param piOffset offset in the original array to start reading bytes from
  * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
  *
  * @return short representation of the bytes
  */
 public static short byteArrayToShort(byte[] paRawBytes, int piOffset, boolean pbBigEndian)
 {
   int iRetVal = -1;
   // TODO: revisit this: should we silently add missing byte and should
   // we ingnore excessing bytes?
   if(paRawBytes.length < piOffset + 2)
     return -1;
   int iLow;
   int iHigh;
   if(pbBigEndian)
   {
     iLow  = paRawBytes[piOffset + 1];
     iHigh = paRawBytes[piOffset + 0];
   }
   else
   {
     iLow  = paRawBytes[piOffset + 0];
     iHigh = paRawBytes[piOffset + 1];
   }
   // Merge high-order and low-order byte to form a 16-bit double value.
   iRetVal = (iHigh << 8) | (0xFF & iLow);
   return (short)iRetVal;
 }
 /**
  * Converts a byte array to int value.
  * Equivalent to intArrayToShort(paRawBytes, 0, pbBigEndian);
  *
  * @param paRawBytes the byte array
  * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
  *
  * @return int representation of the bytes
  */
 public static int byteArrayToInt(byte[] paRawBytes, boolean pbBigEndian)
 {
   return byteArrayToInt(paRawBytes, 0, pbBigEndian);
 }
 /**
  * Converts a portion of a byte array with given offset to int value.
  *
  * @param paRawBytes the byte array
  * @param piOffset offset in the original array to start reading bytes from
  * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
  *
  * @return int representation of the bytes
  */
 public static int byteArrayToInt(byte[] paRawBytes, int piOffset, boolean pbBigEndian)
 {
   int iRetVal = -1;
   if(paRawBytes.length < piOffset + 4)
     return iRetVal;
   int iLowest;
   int iLow;
   int iMid;
   int iHigh;
   if(pbBigEndian)
   {
     iLowest = paRawBytes[piOffset + 3];
     iLow    = paRawBytes[piOffset + 2];
     iMid    = paRawBytes[piOffset + 1];
     iHigh   = paRawBytes[piOffset + 0];
   }
   else
   {
     iLowest = paRawBytes[piOffset + 0];
     iLow    = paRawBytes[piOffset + 1];
     iMid    = paRawBytes[piOffset + 2];
     iHigh   = paRawBytes[piOffset + 3];
   }
   // Merge four bytes to form a 32-bit int value.
   iRetVal = (iHigh << 24) | (iMid << 16) | (iLow << 8) | (0xFF & iLowest);
   return iRetVal;
 }
 /**
  * Converts an int value to a byte array.
  *
  * @param piValueToConvert the original integer
  * @param pbBigEndian true if the bytes are in Big-endian order; false otherwise
  *
  * @return byte[] representation of the int
  */
 public static byte[] intToByteArray(int piValueToConvert, boolean pbBigEndian)
 {
   byte[] aRetVal = new byte[4];
   byte iLowest;
   byte iLow;
   byte iMid;
   byte iHigh;
   iLowest = (byte)(piValueToConvert & 0xFF);
   iLow    = (byte)((piValueToConvert >> 8) & 0xFF);
   iMid    = (byte)((piValueToConvert >> 16) & 0xFF);
   iHigh   = (byte)((piValueToConvert >> 24) & 0xFF);
   if(pbBigEndian)
   {
     aRetVal[3] = iLowest;
     aRetVal[2] = iLow;
     aRetVal[1] = iMid;
     aRetVal[0] = iHigh;
   }
   else
   {
     aRetVal[0] = iLowest;
     aRetVal[1] = iLow;
     aRetVal[2] = iMid;
     aRetVal[3] = iHigh;
   }
   return aRetVal;
 }
 /**
  * Converts a byte array to String value.
  * Cleans up non-word characters along the way.
  *
  * Equivalent to byteArrayToString(paRawBytes, 0, paRawBytes.length);
  *
  * @param paRawBytes the byte array, non-UNICODE
  *
  * @return UNICODE String representation of the bytes
  */
 public static String byteArrayToString(byte[] paRawBytes)
 {
   return byteArrayToString(paRawBytes, 0, paRawBytes.length);
 }
 /**
  * Converts a portion of a byte array to String value.
  * Cleans up non-word characters along the way.
  *
  * @param paRawBytes the byte array, non-UNICODE
  * @param piOffset offset in the original array to start reading bytes from
  * @param piLength how many bytes of the array paramter to interpret as String
  *
  * @return UNICODE String representation of the bytes with trailing garbage stripped;
  *         "" if array length is less than piOffset + piLength;
  *         "" if the generatied string begins with garbage
  */
 public static String byteArrayToString(byte[] paRawBytes, int piOffset, int piLength)
 {
   if(paRawBytes.length < piOffset + piLength)
     return "";
   String oBeautifulString = new String(paRawBytes, piOffset, piLength);
   int i = 0;
   if(oBeautifulString.matches("^\\W") == true)
     oBeautifulString = "";
   else
   {
     for(i = piOffset; i < piOffset + piLength; i++)
     {
       if(paRawBytes[i] < 32 || paRawBytes[i] > 128)
         break;
     }
     oBeautifulString = oBeautifulString.substring(0, i - piOffset);
   }
   return oBeautifulString;
 }
 /**
  * Converts a String value to a byte array in US-ASCII charset.
  *
  * Equivalent to stringToByteArray(pstrStringToConvert, "US-ASCII");
  *
  * @param pstrStringToConvert the original string
  *
  * @return null-terminated byte[] representation of the String
  */
 public static byte[] stringToByteArray(String pstrStringToConvert)
 {
   return stringToByteArray(pstrStringToConvert, "US-ASCII");
 }
 /**
  * Attempts to convert a String value to a byte array in specified charset.
  * If the charset is invalid, returns plain byte-representation of the host environment.
  *
  * @param pstrStringToConvert the original string
  * @param pstrCharSet characted set to assume for the original string
  *
  * @return null-terminated byte[] representation of the String
  */
 public static byte[] stringToByteArray(String pstrStringToConvert, String pstrCharSet)
 {
   byte[] aRecordData = null;
   try
   {
     aRecordData = (pstrStringToConvert + "\0").getBytes(pstrCharSet);
   }
   catch(UnsupportedEncodingException e)
   {
     System.err.println("WARNING: " + e);
     aRecordData = (pstrStringToConvert + "\0").getBytes();
   }
   return aRecordData;
 }
   /**
  * Returns source code revision information.
  * @return revision string
  */
 public static String getMARFSourceCodeRevision()
 {
   return "$Revision: 1.6 $";
 }

} // EOF




 </source>
   
  
 
  



ByteArray wraps java byte arrays (byte[]) to allow byte arrays to be used as keys in hashtables.

   <source lang="java">
     

/*

  Derby - Class org.apache.derby.iapi.util.ByteArray
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to you under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

import java.io.ObjectOutput; import java.io.ObjectInput; import java.io.IOException; /**

 ByteArray wraps java byte arrays (byte[]) to allow
 byte arrays to be used as keys in hashtables.
 This is required because the equals function on
 byte[] directly uses reference equality.

This class also allows the trio of array, offset and length to be carried around as a single object.

  • /
public final class ByteArray { private byte[] array; private int offset; private int length; /** Create an instance of this class that wraps ths given array. This class does not make a copy of the array, it just saves the reference. */ public ByteArray(byte[] array, int offset, int length) { this.array = array; this.offset = offset; this.length = length; } public ByteArray(byte[] array) { this(array, 0, array.length); } public ByteArray() { } public void setBytes(byte[] array) { this.array = array; offset = 0; length = array.length; } public void setBytes(byte[] array, int length) { this.array = array; this.offset = 0; this.length = length; } public void setBytes(byte[] array, int offset, int length) { this.array = array; this.offset = offset; this.length = length; } /** Value equality for byte arrays. */ public boolean equals(Object other) { if (other instanceof ByteArray) { ByteArray ob = (ByteArray) other; return ByteArray.equals(array, offset, length, ob.array, ob.offset, ob.length); } return false; } /** */ public int hashCode() { byte[] larray = array; int hash = length; for (int i = 0; i < length; i++) { hash += larray[i + offset]; } return hash; } public final byte[] getArray() { return array; } public final int getOffset() { return offset; } public final int getLength() { return length; } public final void setLength(int newLength) { length = newLength; } /** * Read this object from a stream of stored objects. * * @param in read this. * * @exception IOException thrown on error */ public void readExternal( ObjectInput in ) throws IOException { int len = length = in.readInt(); offset = 0; array = new byte[len]; in.readFully(array, 0, len); } /** * Write the byte array out w/o compression * * @param out write bytes here. * * @exception IOException thrown on error */ public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(length); out.write(array, offset, length); } /** Compare two byte arrays using value equality. Two byte arrays are equal if their length is identical and their contents are identical. */ private static boolean equals(byte[] a, int aOffset, int aLength, byte[] b, int bOffset, int bLength) { if (aLength != bLength) return false; for (int i = 0; i < aLength; i++) { if (a[i + aOffset] != b[i + bOffset]) return false; } return true; } } </source>

Compare two byte[] for differences, either may be null

   <source lang="java">
   

import java.util.Collection; import java.util.Iterator; /**********************************************************************************

* $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/StringUtil.java $
* $Id: StringUtil.java 34934 2007-09-10 22:52:23Z lance@indiana.edu $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
* 
* Licensed under the Educational Community License, Version 1.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at
* 
*      http://www.opensource.org/licenses/ecl1.php
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed under the License is distributed on an "AS IS" BASIS, 
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
**********************************************************************************/

/**

* <p>
* StringUtil collects together some string utility classes.
*

*/

public class StringUtil {

 /**
  * Compare two byte[] for differences, either may be null
  * 
  * @param a
  *        One byte[].
  * @param b
  *        The other byte[].
  * @return true if the byte[]s are different, false if they are the same.
  */
 public static boolean different(byte[] a, byte[] b)
 {
   // if both null, they are the same
   if ((a == null) && (b == null)) return false;
   // if either are null (they both are not), they are different
   if ((a == null) || (b == null)) return true;
   // if the lengths are different, they are different
   if (a.length != b.length) return true;
   // now we know neither are null, so compare, item for item (order counts)
   for (int i = 0; i < a.length; i++)
   {
     if (a[i] != b[i]) return true;
   }
   // they are NOT different!
   return false;
 }

}



 </source>
   
  
 
  



Convert byte array into a printable format: a String of hexadecimal digit characters (two per byte).

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.ByteArrayOutputStream; /**

* Library of utility methods useful in dealing with converting byte arrays to
* and from strings of hexadecimal digits.
* 
* @author Craig R. McClanahan
*/

public class Utils {

 /**
  * Convert a byte array into a printable format containing a String of
  * hexadecimal digit characters (two per byte).
  * 
  * @param bytes
  *          Byte array representation
  */
 public static String convert(byte bytes[]) {
   StringBuffer sb = new StringBuffer(bytes.length * 2);
   for (int i = 0; i < bytes.length; i++) {
     sb.append(convertDigit((int) (bytes[i] >> 4)));
     sb.append(convertDigit((int) (bytes[i] & 0x0f)));
   }
   return (sb.toString());
 }
 /**
  * [Private] Convert the specified value (0 .. 15) to the corresponding
  * hexadecimal digit.
  * 
  * @param value
  *          Value to be converted
  */
 private static char convertDigit(int value) {
   value &= 0x0f;
   if (value >= 10)
     return ((char) (value - 10 + "a"));
   else
     return ((char) (value + "0"));
 }

}

 </source>
   
  
 
  



Convert hexadecimal digits into byte array by encoding each two hexadecimal digits as a byte.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.ByteArrayOutputStream; /**

* Library of utility methods useful in dealing with converting byte arrays to
* and from strings of hexadecimal digits.
* 
* @author Craig R. McClanahan
*/

public class Utils {

 /**
  * Convert a String of hexadecimal digits into the corresponding byte array by
  * encoding each two hexadecimal digits as a byte.
  * 
  * @param digits
  *          Hexadecimal digits representation
  * 
  * @exception IllegalArgumentException
  *              if an invalid hexadecimal digit is found, or the input string
  *              contains an odd number of hexadecimal digits
  */
 public static byte[] convert(String digits) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   for (int i = 0; i < digits.length(); i += 2) {
     char c1 = digits.charAt(i);
     if ((i + 1) >= digits.length())
       throw new IllegalArgumentException("hexUtil.odd");
     char c2 = digits.charAt(i + 1);
     byte b = 0;
     if ((c1 >= "0") && (c1 <= "9"))
       b += ((c1 - "0") * 16);
     else if ((c1 >= "a") && (c1 <= "f"))
       b += ((c1 - "a" + 10) * 16);
     else if ((c1 >= "A") && (c1 <= "F"))
       b += ((c1 - "A" + 10) * 16);
     else
       throw new IllegalArgumentException("hexUtil.bad");
     if ((c2 >= "0") && (c2 <= "9"))
       b += (c2 - "0");
     else if ((c2 >= "a") && (c2 <= "f"))
       b += (c2 - "a" + 10);
     else if ((c2 >= "A") && (c2 <= "F"))
       b += (c2 - "A" + 10);
     else
       throw new IllegalArgumentException("hexUtil.bad");
     baos.write(b);
   }
   return (baos.toByteArray());
 }

}

 </source>
   
  
 
  



Converts a byte array into a hexadecimal string

   <source lang="java">
   

/* Copyright (c) 1995-2000, The Hypersonic SQL Group.

* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the Hypersonic SQL Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE HYPERSONIC SQL GROUP,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* on behalf of the Hypersonic SQL Group.
*
*
* For work added by the HSQL Development Group:
*
* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**

* Collection of static methods for converting strings between different formats
* and to and from byte arrays.
*

* * Includes some methods based on Hypersonic code as indicated. * * @author Thomas Mueller (Hypersonic SQL Group) * @author Fred Toussi (fredt@users dot sourceforge.net) * @version 1.9.0 * @since 1.7.2 */ public class Main { private static final byte[] HEXBYTES = { (byte) "0", (byte) "1", (byte) "2", (byte) "3", (byte) "4", (byte) "5", (byte) "6", (byte) "7", (byte) "8", (byte) "9", (byte) "a", (byte) "b", (byte) "c", (byte) "d", (byte) "e", (byte) "f" }; /** * Converts a byte array into a hexadecimal string * * * @param b * byte array * * @return hex string */ public static String byteArrayToHexString(byte[] b) { int len = b.length; char[] s = new char[len * 2]; for (int i = 0, j = 0; i < len; i++) { int c = ((int) b[i]) & 0xff; s[j++] = (char) HEXBYTES[c >> 4 & 0xf]; s[j++] = (char) HEXBYTES[c & 0xf]; } return new String(s); } } </source>

Converts a byte array into hexadecimal characters which are written as ASCII to the given output stream.

   <source lang="java">
   
  
  

/* Copyright (c) 1995-2000, The Hypersonic SQL Group.

* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the Hypersonic SQL Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE HYPERSONIC SQL GROUP,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* on behalf of the Hypersonic SQL Group.
*
*
* For work added by the HSQL Development Group:
*
* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**

* Collection of static methods for converting strings between different formats
* and to and from byte arrays.
* <p>
* 
* Includes some methods based on Hypersonic code as indicated.
* 
* @author Thomas Mueller (Hypersonic SQL Group)
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 1.9.0
* @since 1.7.2
*/

public class Main {

 private static final byte[] HEXBYTES = { (byte) "0", (byte) "1", (byte) "2", (byte) "3",
     (byte) "4", (byte) "5", (byte) "6", (byte) "7", (byte) "8", (byte) "9", (byte) "a",
     (byte) "b", (byte) "c", (byte) "d", (byte) "e", (byte) "f" };
 /**
  * Converts a byte array into hexadecimal characters which are written as
  * ASCII to the given output stream.
  *
  * @param o output array
  * @param from offset into output array
  * @param b input array
  */
 public static void writeHexBytes(byte[] o, int from, byte[] b) {
     int len = b.length;
     for (int i = 0; i < len; i++) {
         int c = ((int) b[i]) & 0xff;
         o[from++] = HEXBYTES[c >> 4 & 0xf];
         o[from++] = HEXBYTES[c & 0xf];
     }
 }

}



 </source>
   
  
 
  



Convert the bytes within the specified range of the given byte array into a signed integer

   <source lang="java">
   

/*

* The contents of this file are subject to the terms 
* of the Common Development and Distribution License 
* (the "License").  You may not use this file except 
* in compliance with the License.
* 
* You can obtain a copy of the license at 
* glassfish/bootstrap/legal/CDDLv1.0.txt or 
* https://glassfish.dev.java.net/public/CDDLv1.0.html. 
* See the License for the specific language governing 
* permissions and limitations under the License.
* 
* When distributing Covered Code, include this CDDL 
* HEADER in each file and include the License file at 
* glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
* add the following below this CDDL HEADER, with the 
* fields enclosed by brackets "[]" replaced with your 
* own identifying information: Portions Copyright [yyyy] 
* [name of copyright owner]
*/

/*

* @(#)ASCIIUtility.java  1.10 05/08/29
*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
*/

public class Utils {

 /**
  * Convert the bytes within the specified range of the given byte array into a
  * signed integer . The range extends from start till, but not
  * including end.
  * <p>
  */
 public static int parseInt(byte[] b, int start, int end) throws NumberFormatException {
   return parseInt(b, start, end, 10);
 }
 /**
  * Convert the bytes within the specified range of the given byte array into a
  * signed integer in the given radix . The range extends from
  * start till, but not including end.
  * <p>
  * 
  * Based on java.lang.Integer.parseInt()
  */
 public static int parseInt(byte[] b, int start, int end, int radix) throws NumberFormatException {
   if (b == null)
     throw new NumberFormatException("null");
   int result = 0;
   boolean negative = false;
   int i = start;
   int limit;
   int multmin;
   int digit;
   if (end > start) {
     if (b[i] == "-") {
       negative = true;
       limit = Integer.MIN_VALUE;
       i++;
     } else {
       limit = -Integer.MAX_VALUE;
     }
     multmin = limit / radix;
     if (i < end) {
       digit = Character.digit((char) b[i++], radix);
       if (digit < 0) {
         throw new NumberFormatException("illegal number: " + toString(b, start, end));
       } else {
         result = -digit;
       }
     }
     while (i < end) {
       // Accumulating negatively avoids surprises near MAX_VALUE
       digit = Character.digit((char) b[i++], radix);
       if (digit < 0) {
         throw new NumberFormatException("illegal number");
       }
       if (result < multmin) {
         throw new NumberFormatException("illegal number");
       }
       result *= radix;
       if (result < limit + digit) {
         throw new NumberFormatException("illegal number");
       }
       result -= digit;
     }
   } else {
     throw new NumberFormatException("illegal number");
   }
   if (negative) {
     if (i > start + 1) {
       return result;
     } else { /* Only got "-" */
       throw new NumberFormatException("illegal number");
     }
   } else {
     return -result;
   }
 }
 /**
  * Convert the bytes within the specified range of the given byte array into a
  * String. The range extends from start till, but not including
  * end.
  * <p>
  */
 public static String toString(byte[] b, int start, int end) {
   int size = end - start;
   char[] theChars = new char[size];
   for (int i = 0, j = start; i < size;)
     theChars[i++] = (char) (b[j++] & 0xff);
   return new String(theChars);
 }

}



 </source>
   
  
 
  



Convert the bytes within the specified range of the given byte array into a signed integer in the given radix

   <source lang="java">
   

/*

* The contents of this file are subject to the terms 
* of the Common Development and Distribution License 
* (the "License").  You may not use this file except 
* in compliance with the License.
* 
* You can obtain a copy of the license at 
* glassfish/bootstrap/legal/CDDLv1.0.txt or 
* https://glassfish.dev.java.net/public/CDDLv1.0.html. 
* See the License for the specific language governing 
* permissions and limitations under the License.
* 
* When distributing Covered Code, include this CDDL 
* HEADER in each file and include the License file at 
* glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
* add the following below this CDDL HEADER, with the 
* fields enclosed by brackets "[]" replaced with your 
* own identifying information: Portions Copyright [yyyy] 
* [name of copyright owner]
*/

/*

* @(#)ASCIIUtility.java  1.10 05/08/29
*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
*/

public class Utils {

 /**
  * Convert the bytes within the specified range of the given byte array into a
  * signed integer in the given radix . The range extends from
  * start till, but not including end.
  * <p>
  * 
  * Based on java.lang.Integer.parseInt()
  */
 public static int parseInt(byte[] b, int start, int end, int radix) throws NumberFormatException {
   if (b == null)
     throw new NumberFormatException("null");
   int result = 0;
   boolean negative = false;
   int i = start;
   int limit;
   int multmin;
   int digit;
   if (end > start) {
     if (b[i] == "-") {
       negative = true;
       limit = Integer.MIN_VALUE;
       i++;
     } else {
       limit = -Integer.MAX_VALUE;
     }
     multmin = limit / radix;
     if (i < end) {
       digit = Character.digit((char) b[i++], radix);
       if (digit < 0) {
         throw new NumberFormatException("illegal number: " + toString(b, start, end));
       } else {
         result = -digit;
       }
     }
     while (i < end) {
       // Accumulating negatively avoids surprises near MAX_VALUE
       digit = Character.digit((char) b[i++], radix);
       if (digit < 0) {
         throw new NumberFormatException("illegal number");
       }
       if (result < multmin) {
         throw new NumberFormatException("illegal number");
       }
       result *= radix;
       if (result < limit + digit) {
         throw new NumberFormatException("illegal number");
       }
       result -= digit;
     }
   } else {
     throw new NumberFormatException("illegal number");
   }
   if (negative) {
     if (i > start + 1) {
       return result;
     } else { /* Only got "-" */
       throw new NumberFormatException("illegal number");
     }
   } else {
     return -result;
   }
 }
 /**
  * Convert the bytes within the specified range of the given byte array into a
  * String. The range extends from start till, but not including
  * end.
  * <p>
  */
 public static String toString(byte[] b, int start, int end) {
   int size = end - start;
   char[] theChars = new char[size];
   for (int i = 0, j = start; i < size;)
     theChars[i++] = (char) (b[j++] & 0xff);
   return new String(theChars);
 }

}



 </source>
   
  
 
  



Convert the bytes within the specified range of the given byte array into a signed long

   <source lang="java">
   

/*

* The contents of this file are subject to the terms 
* of the Common Development and Distribution License 
* (the "License").  You may not use this file except 
* in compliance with the License.
* 
* You can obtain a copy of the license at 
* glassfish/bootstrap/legal/CDDLv1.0.txt or 
* https://glassfish.dev.java.net/public/CDDLv1.0.html. 
* See the License for the specific language governing 
* permissions and limitations under the License.
* 
* When distributing Covered Code, include this CDDL 
* HEADER in each file and include the License file at 
* glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
* add the following below this CDDL HEADER, with the 
* fields enclosed by brackets "[]" replaced with your 
* own identifying information: Portions Copyright [yyyy] 
* [name of copyright owner]
*/

/*

* @(#)ASCIIUtility.java  1.10 05/08/29
*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
*/

public class Utils {

 /**
  * Convert the bytes within the specified range of the given byte array into a
  * signed long . The range extends from start till, but not
  * including end.
  * <p>
  */
 public static long parseLong(byte[] b, int start, int end) throws NumberFormatException {
   return parseLong(b, start, end, 10);
 }
 /**
  * Convert the bytes within the specified range of the given byte array into a
  * signed long in the given radix . The range extends from start
  * till, but not including end.
  * <p>
  * 
  * Based on java.lang.Long.parseLong()
  */
 public static long parseLong(byte[] b, int start, int end, int radix)
     throws NumberFormatException {
   if (b == null)
     throw new NumberFormatException("null");
   long result = 0;
   boolean negative = false;
   int i = start;
   long limit;
   long multmin;
   int digit;
   if (end > start) {
     if (b[i] == "-") {
       negative = true;
       limit = Long.MIN_VALUE;
       i++;
     } else {
       limit = -Long.MAX_VALUE;
     }
     multmin = limit / radix;
     if (i < end) {
       digit = Character.digit((char) b[i++], radix);
       if (digit < 0) {
         throw new NumberFormatException("illegal number: " + toString(b, start, end));
       } else {
         result = -digit;
       }
     }
     while (i < end) {
       // Accumulating negatively avoids surprises near MAX_VALUE
       digit = Character.digit((char) b[i++], radix);
       if (digit < 0) {
         throw new NumberFormatException("illegal number");
       }
       if (result < multmin) {
         throw new NumberFormatException("illegal number");
       }
       result *= radix;
       if (result < limit + digit) {
         throw new NumberFormatException("illegal number");
       }
       result -= digit;
     }
   } else {
     throw new NumberFormatException("illegal number");
   }
   if (negative) {
     if (i > start + 1) {
       return result;
     } else { /* Only got "-" */
       throw new NumberFormatException("illegal number");
     }
   } else {
     return -result;
   }
 }
 /**
  * Convert the bytes within the specified range of the given byte array into a
  * String. The range extends from start till, but not including
  * end.
  * <p>
  */
 public static String toString(byte[] b, int start, int end) {
   int size = end - start;
   char[] theChars = new char[size];
   for (int i = 0, j = start; i < size;)
     theChars[i++] = (char) (b[j++] & 0xff);
   return new String(theChars);
 }

}



 </source>
   
  
 
  



Convert the bytes within the specified range of the given byte array into a String

   <source lang="java">
   

/*

* The contents of this file are subject to the terms 
* of the Common Development and Distribution License 
* (the "License").  You may not use this file except 
* in compliance with the License.
* 
* You can obtain a copy of the license at 
* glassfish/bootstrap/legal/CDDLv1.0.txt or 
* https://glassfish.dev.java.net/public/CDDLv1.0.html. 
* See the License for the specific language governing 
* permissions and limitations under the License.
* 
* When distributing Covered Code, include this CDDL 
* HEADER in each file and include the License file at 
* glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
* add the following below this CDDL HEADER, with the 
* fields enclosed by brackets "[]" replaced with your 
* own identifying information: Portions Copyright [yyyy] 
* [name of copyright owner]
*/

/*

* @(#)ASCIIUtility.java  1.10 05/08/29
*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
*/

public class Utils {

 /**
  * Convert the bytes within the specified range of the given byte array into a
  * String. The range extends from start till, but not including
  * end.
  * <p>
  */
 public static String toString(byte[] b, int start, int end) {
   int size = end - start;
   char[] theChars = new char[size];
   for (int i = 0, j = start; i < size;)
     theChars[i++] = (char) (b[j++] & 0xff);
   return new String(theChars);
 }

}



 </source>
   
  
 
  



Decode byte array

   <source lang="java">
    

/* Copyright 2004 The Apache Software Foundation

*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*  limitations under the License.
*/

//xmlbeans import java.io.UnsupportedEncodingException; /**

* format validation
*
* This class encodes/decodes hexadecimal data
* @author Jeffrey Rodriguez
* @version $Id: HexBin.java 125124 2005-01-14 00:23:54Z kkrouse $
*/

public class Main {

 static private final int  BASELENGTH   = 255;
 static private final int  LOOKUPLENGTH = 16;
 static private byte [] hexNumberTable    = new byte[BASELENGTH];
 static private byte [] lookUpHexAlphabet = new byte[LOOKUPLENGTH];
 static {
     for (int i = 0; i<BASELENGTH; i++ ) {
         hexNumberTable[i] = -1;
     }
     for ( int i = "9"; i >= "0"; i--) {
         hexNumberTable[i] = (byte) (i-"0");
     }
     for ( int i = "F"; i>= "A"; i--) {
         hexNumberTable[i] = (byte) ( i-"A" + 10 );
     }
     for ( int i = "f"; i>= "a"; i--) {
        hexNumberTable[i] = (byte) ( i-"a" + 10 );
     }
     for(int i = 0; i<10; i++ )
         lookUpHexAlphabet[i] = (byte) ("0"+i );
     for(int i = 10; i<=15; i++ )
         lookUpHexAlphabet[i] = (byte) ("A"+i -10);
 }
 static public byte[] decode(byte[] binaryData) {
     if (binaryData == null)
         return null;
     int lengthData   = binaryData.length;
     if (lengthData % 2 != 0)
         return null;
     int lengthDecode = lengthData / 2;
     byte[] decodedData = new byte[lengthDecode];
     for( int i = 0; i<lengthDecode; i++ ){
         if (!isHex(binaryData[i*2]) || !isHex(binaryData[i*2+1])) {
             return null;
         }
         decodedData[i] = (byte)((hexNumberTable[binaryData[i*2]] << 4) | hexNumberTable[binaryData[i*2+1]]);
     }
     return decodedData;
 }
 /**
  * byte to be tested if it is Base64 alphabet
  *
  * @param octect
  * @return
  */
 static boolean isHex(byte octect) {
     return (hexNumberTable[octect] != -1);
 }

}



 </source>
   
  
 
  



Gets an array of bytes corresponding to the given object

   <source lang="java">
     

/**

* EasyBeans
* Copyright (C) 2006 Bull S.A.S.
* Contact: easybeans@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: Serialization.java 1970 2007-10-16 11:49:25Z benoitf $
* --------------------------------------------------------------------------
*/

import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; /**

* Allow to get the bytes of an object or to recreate an object from bytes.
* It also used a custom reader when recreating object as it uses the context * classloader in order to have an object with the right classloader. * @author Florent Benoit */

public final class Serialization {

   /**
    * Gets an array of bytes corresponding to the given object.
    * @param object the object to serialize
    * @return an array of bytes.
    * @throws IOException if the object can"t be turned into an array of bytes.
    */
   public static byte[] storeObject(final Serializable object) throws IOException {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       ObjectOutputStream oos  =  null;
       try {
           oos = new ObjectOutputStream(baos);
           oos.writeObject(object);
           oos.flush();
           return baos.toByteArray();
       } finally {
           if (oos != null)  {
               oos.close();
           }
           if (baos != null) {
               baos.close();
           }
       }
   }

}




 </source>
   
  
 
  



Given a hexstring this will return the byte array corresponding to string

   <source lang="java">
    

/**

* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.StringTokenizer; import java.util.Collection;

/**

* General string utils
*/

public class StringUtils {

 final public static char COMMA = ",";
 final public static String COMMA_STR = ",";
 final public static char ESCAPE_CHAR = "\\";
 private static DecimalFormat oneDecimal = new DecimalFormat("0.0");
 
 /**
  * Given a hexstring this will return the byte array corresponding to the
  * string
  * @param hex the hex String array
  * @return a byte array that is a hex string representation of the given
  *         string. The size of the byte array is therefore hex.length/2
  */
 public static byte[] hexStringToByte(String hex) {
   byte[] bts = new byte[hex.length() / 2];
   for (int i = 0; i < bts.length; i++) {
     bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
   }
   return bts;
 }

}



 </source>
   
  
 
  



Load File as byte array

   <source lang="java">
    

/*

   GNU LESSER GENERAL PUBLIC LICENSE
   Copyright (C) 2006 The Lobo Project
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   Contact info: lobochief@users.sourceforge.net
  • /

/*

* Created on Mar 19, 2005
*/

import java.io.*; /**

* @author J. H. S.
*/

public class IORoutines {

 public static final byte[] LINE_BREAK_BYTES = { (byte) 13, (byte) 10 }; 
 
 public static String loadAsText(InputStream in, String encoding) throws IOException {
   return loadAsText(in, encoding, 4096);
 }
 
 public static String loadAsText(InputStream in, String encoding, int bufferSize) throws IOException {
   InputStreamReader reader = new InputStreamReader(in, encoding);
     char[] buffer = new char[bufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         char[] newBuffer = new char[buffer.length * 2];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = reader.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     return new String(buffer, 0, offset);
 }
 
   public static byte[] load(File file) throws IOException {
       long fileLength = file.length();
       if(fileLength > Integer.MAX_VALUE) {
           throw new IOException("File "" + file.getName() + "" too big");
       }
       InputStream in = new FileInputStream(file);
       try {
         return loadExact(in, (int) fileLength);
       } finally {
           in.close();
       }
   }
   
   public static byte[] load(InputStream in) throws IOException {
       return load(in, 4096);
   }
   public static byte[] load(InputStream in, int initialBufferSize) throws IOException {
     if(initialBufferSize == 0) {
       initialBufferSize = 1;
     }
     byte[] buffer = new byte[initialBufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         int newSize = buffer.length * 2;
         byte[] newBuffer = new byte[newSize];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = in.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     if(offset < buffer.length) {
       byte[] newBuffer = new byte[offset];
       System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
       buffer = newBuffer;
     }
     return buffer;
   }
   
   public static byte[] loadExact(InputStream in, int length) throws IOException {
     byte[] buffer = new byte[length];
     int offset = 0;
     for(;;) {
       int remain = length - offset;
       if(remain <= 0) {
         break;
       }
       int numRead = in.read(buffer, offset, remain);
       if(numRead == -1) {
         throw new IOException("Reached EOF, read " + offset + " expecting " + length);
       }
     offset += numRead;
     }
     return buffer;
   }
   public static boolean equalContent(File file, byte[] content) throws IOException {
     long length = file.length();
     if(length > Integer.MAX_VALUE) {
       throw new IOException("File "" + file + "" too big");
     }
     InputStream in = new FileInputStream(file);
     try {
       byte[] fileContent = loadExact(in, (int) length);
       return java.util.Arrays.equals(content, fileContent);
     } finally {
       in.close();
     }
   }
   
   public static void save(File file, byte[] content) throws IOException {
     FileOutputStream out = new FileOutputStream(file);
     try {
       out.write(content);
     } finally {
       out.close();
     }
   }
   
   /**
    * Reads line without buffering.
    */
   public static String readLine(InputStream in) throws IOException {
     int b;
     StringBuffer sb = null;
     OUTER:
     while((b = in.read()) != -1) {
       if(sb == null) {
         sb = new StringBuffer();
       }
       switch(b) {
         case (byte) "\n":
           break OUTER;
         case (byte) "\r":
           break;
         default:
           sb.append((char) b);
           break;
       }
     }
     return sb == null ? null : sb.toString();
   }
   
   public static void touch(File file) {
     file.setLastModified(System.currentTimeMillis());
   }
   
   public static void saveStrings(File file, java.util.Collection list) throws IOException {
     BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file));
     try {
       PrintWriter writer = new PrintWriter(bout);
       java.util.Iterator i = list.iterator();
       while(i.hasNext()) {
         String text = (String) i.next();
         writer.println(text);
       }
       writer.flush();
     } finally {
       bout.close();
     }
   }
   
   public static java.util.List loadStrings(File file) throws IOException {
     java.util.List list = new java.util.LinkedList();
     InputStream in = new FileInputStream(file);
     try {
       BufferedReader reader = new BufferedReader(new InputStreamReader(in));
       String line;
       while((line = reader.readLine()) != null) {
         list.add(line);
       }
       return list;
     } finally {
       in.close();
     }
   }
   

}



 </source>
   
  
 
  



Load file to byte array

   <source lang="java">
     

/******************************************************************

  • CyberUtil for Java
  • Copyright (C) Satoshi Konno 2002-2003
  • File: FileUtil.java
  • Revision:
  • 01/03/03
  • - first revision.
                                                                                                                                    • /

import java.io.*; public final class FileUtil {

 public final static byte[] load(String fileName)
 {
   try { 
     FileInputStream fin=new FileInputStream(fileName);
     return load(fin);
   }
   catch (Exception e) {

     return new byte[0];
   }
 }
 public final static byte[] load(File file)
 {
   try { 
     FileInputStream fin=new FileInputStream(file);
     return load(fin);
   }
   catch (Exception e) {
    
     return new byte[0];
   }
 }
 public final static byte[] load(FileInputStream fin)
 {
   byte readBuf[] = new byte[512*1024];
 
   try { 
     ByteArrayOutputStream bout = new ByteArrayOutputStream();
   
     int readCnt = fin.read(readBuf);
     while (0 < readCnt) {
       bout.write(readBuf, 0, readCnt);
       readCnt = fin.read(readBuf);
     }
     
     fin.close();
     
     return bout.toByteArray();
   }
   catch (Exception e) {
    
     return new byte[0];
   }
 }
 

}




 </source>
   
  
 
  



Manages fixed-length byte arrays

   <source lang="java">
     

/*

* dbXML - Native XML Database
* Copyright (C) 1999-2004  The dbXML Group, L.L.C.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*
* $Id: ByteArray.java,v 1.3 2004/07/20 20:19:42 bradford Exp $
*/

/**

* ByteArray manages fixed-length byte arrays
*/

public final class ByteArray {

  private byte[] data;
  private int offset;
  private int length;
  private int pos;
  private ByteArray() {
  }
  public ByteArray(int size) {
     data = new byte[size];
     offset = 0;
     length = size;
     pos = 0;
  }
  public ByteArray(byte[] data, int offset, int length) {
     this.data = data;
     this.offset = offset;
     this.length = length;
     this.pos = 0;
  }
  public ByteArray(byte[] data) {
     this.data = data;
     offset = 0;
     length = data.length;
     pos = 0;
  }
  public byte[] getData() {
     return data;
  }
  public int getLength() {
     return length;
  }
  public int getOffset() {
     return offset;
  }
  public int getPos() {
     return pos;
  }
  public void setPos(int pos) {
     if ( pos >= 0 && pos < length )
        this.pos = pos;
  }
  public void resetPos() {
     pos = offset;
  }
  public static long readLong(byte[] data, int offset) {
     int ch1 = data[offset] & 0xff;
     int ch2 = data[offset + 1] & 0xff;
     int ch3 = data[offset + 2] & 0xff;
     int ch4 = data[offset + 3] & 0xff;
     int ch5 = data[offset + 4] & 0xff;
     int ch6 = data[offset + 5] & 0xff;
     int ch7 = data[offset + 6] & 0xff;
     int ch8 = data[offset + 7] & 0xff;
     return (ch1 << 56) + (ch2 << 48) + (ch3 << 40) + (ch4 << 32)
        + (ch5 << 24) + (ch6 << 16) + (ch7 << 8) + (ch8 << 0);
  }
  public long readLong() {
     long result = readLong(data, pos);
     pos += 8;
     return result;
  }
  public static int readInt(byte[] data, int offset) {
     int ch1 = data[offset] & 0xff;
     int ch2 = data[offset + 1] & 0xff;
     int ch3 = data[offset + 2] & 0xff;
     int ch4 = data[offset + 3] & 0xff;
     return (ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0);
  }
  public int readInt() {
     int result = readInt(data, pos);
     pos += 4;
     return result;
  }
  public static short readShort(byte[] data, int offset) {
     int ch1 = data[offset] & 0xff;
     int ch2 = data[offset + 1] & 0xff;
     return (short)((ch1 << 8) + (ch2 << 0));
  }
  public short readShort() {
     short result = readShort(data, pos);
     pos += 2;
     return result;
  }
  public static char readChar(byte[] data, int offset) {
     int ch1 = data[offset] & 0xff;
     int ch2 = data[offset + 1] & 0xff;
     return (char)((ch1 << 8) + (ch2 << 0));
  }
  public char readChar() {
     char result = readChar(data, pos);
     pos += 2;
     return result;
  }
  public static byte readByte(byte[] data, int offset) {
     return data[offset];
  }
  public byte readByte() {
     return data[pos++];
  }
  public static void readBytes(byte[] data, int offset, byte[] buffer, int pos, int length) {
     System.arraycopy(data, offset, buffer, pos, length);
  }
  public ByteArray readBytes(byte[] buffer, int offset, int length) {
     System.arraycopy(data, pos, buffer, offset, length);
     pos += length;
     return this;
  }
  public static void readBytes(byte[] data, int offset, byte[] buffer) {
     readBytes(data, offset, buffer, 0, buffer.length);
  }
  public ByteArray readBytes(byte[] buffer) {
     return readBytes(buffer, 0, buffer.length);
  }
  public static void writeLong(byte[] data, int offset, long value) {
     data[offset] = (byte)((value >>> 56) & 0xFF);
     data[offset + 1] = (byte)((value >>> 48) & 0xFF);
     data[offset + 2] = (byte)((value >>> 40) & 0xFF);
     data[offset + 3] = (byte)((value >>> 32) & 0xFF);
     data[offset + 4] = (byte)((value >>> 24) & 0xFF);
     data[offset + 5] = (byte)((value >>> 16) & 0xFF);
     data[offset + 6] = (byte)((value >>> 8) & 0xFF);
     data[offset + 7] = (byte)((value >>> 0) & 0xFF);
  }
  public ByteArray writeLong(long value) {
     writeLong(data, pos, value);
     pos += 8;
     return this;
  }
  public static void writeInt(byte[] data, int offset, int value) {
     data[offset] = (byte)((value >>> 24) & 0xFF);
     data[offset + 1] = (byte)((value >>> 16) & 0xFF);
     data[offset + 2] = (byte)((value >>> 8) & 0xFF);
     data[offset + 3] = (byte)((value >>> 0) & 0xFF);
  }
  public ByteArray writeInt(int value) {
     writeInt(data, pos, value);
     pos += 4;
     return this;
  }
  public static void writeShort(byte[] data, int offset, short value) {
     data[offset] = (byte)((value >>> 8) & 0xFF);
     data[offset + 1] = (byte)((value >>> 0) & 0xFF);
  }
  public ByteArray writeShort(short value) {
     writeShort(data, pos, value);
     pos += 2;
     return this;
  }
  public static void writeChar(byte[] data, int offset, char value) {
     data[offset] = (byte)((value >>> 8) & 0xFF);
     data[offset + 1] = (byte)((value >>> 0) & 0xFF);
  }
  public ByteArray writeChar(char value) {
     writeChar(data, pos, value);
     pos += 2;
     return this;
  }
  public static void writeByte(byte[] data, int offset, byte value) {
     data[offset] = value;
  }
  public ByteArray writeByte(byte value) {
     data[pos++] = value;
     return this;
  }
  public static void writeBytes(byte[] data, int offset, byte[] buffer, int pos, int length) {
     System.arraycopy(buffer, pos, data, offset, length);
  }
  public ByteArray writeBytes(byte[] buffer, int offset, int length) {
     System.arraycopy(buffer, pos, data, offset, length);
     pos += length;
     return this;
  }
  public static void writeBytes(byte[] data, int offset, byte[] buffer) {
     writeBytes(data, offset, buffer, 0, buffer.length);
  }
  public ByteArray writeBytes(byte[] buffer) {
     return writeBytes(buffer, 0, buffer.length);
  }

}




 </source>
   
  
 
  



Returns a object from the given byte array.

   <source lang="java">
     

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream;

public class Main {

 /**
  * Returns a object from the given byte array.
  * 
  * @param bytes
  *            array to convert
  * @return object
  */
 public static Object bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
     ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
     ObjectInputStream is = new ObjectInputStream(bais);
     return is.readObject();
 }

}




 </source>