I. Pay attention to the following two points:
1. The Object must be a serializable Object.
2. All serializable Object objects can be converted into a disk file. In turn, they are not necessarily true, but only sequential objects.
Object.
Ii. Related conversion methods:
Import java. Io. bufferedoutputstream;
Import java. Io. bytearrayinputstream;
Import java. Io. bytearrayoutputstream;
Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import java. Io. objectinputstream;
Import java. Io. objectoutputstream;
Import java. Io. serializable;
Public class byte_file_object ...{
/***//**
* Convert a file to a byte array
* @ Author Sean. Guo
* @ Edittime 2007-8-13 11:45:28 AM
*/
Public static byte [] getbytesfromfile (file F )...{
If (F = NULL )...{
Return NULL;
}
Try ...{
Fileinputstream stream = new fileinputstream (f );
Bytearrayoutputstream out = new bytearrayoutputstream (1000 );
Byte [] B = new byte [1000];
For (int n; (n = stream. read (B ))! =-1 ;){
Out. write (B, 0, n );
}
Stream. close ();
Out. close ();
Return out. toByteArray ();
} Catch (IOException e )...{
}
Return null;
}
/***//**
* Save the byte array as a file
* @ Author Sean. guo
* @ EditTime 2007-8-13 11:45:56 AM
*/
Public static File getFileFromBytes (byte [] B, String outputFile )...{
BufferedOutputStream stream = null;
File file = null;
Try ...{
File = new File (outputFile );
FileOutputStream fstream = new FileOutputStream (file );
Stream = new BufferedOutputStream (fstream );
Stream. write (B );
} Catch (Exception e )...{
E. printStackTrace ();
} Finally ...{
If (stream! = Null )...{
Try ...{
Stream. close ();
} Catch (IOException e1 )...{
E1.printStackTrace ();
}
}
}
Return file;
}
/***//**
* Get objects from byte Arrays
* @ Author Sean. guo
* @ EditTime 2007-8-13 11:46:34 AM
*/
Public static Object getObjectFromBytes (byte [] objBytes) throws Exception ...{
If (objBytes = null | objBytes. length = 0 )...{
Return null;
}
ByteArrayInputStream bi = new ByteArrayInputStream (objBytes );
ObjectInputStream oi = new ObjectInputStream (bi );
Return oi. readObject ();
}
/***//**
* Get a byte array from an object
* @ Author Sean. guo
* @ EditTime 2007-8-13 11:46:56 AM
*/
Public static byte [] getBytesFromObject (Serializable obj) throws Exception ...{
If (obj = null )...{
Return null;
}
ByteArrayOutputStream bo = new ByteArrayOutputStream ();
ObjectOutputStream oo = new ObjectOutputStream (bo );
Oo. writeObject (obj );
Return bo. toByteArray ();
}
}