Java中File,byte[],Object间的转换
一、有两点需要注意:
1、Object 对象必须是可序列化对象 。
2、可序列化的 Object 对象都可以转换为一个磁盘文件;反过来则不一定成立,只有序列
化文件才可以转换为 Object 对象。
二、相关的转换方法:
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication2;
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;
/**
*
* @author Dao
*/
public class Main
{
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];
int n;
while ((n = stream.read(b)) != -1)
{
out.write(b, 0, n);
}
stream.close();
out.close();
return out.toByteArray();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
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;
}
public static Object lcl_toObject(byte[] bytes)
{
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
ObjectInputStream ois = new ObjectInputStream (bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return obj;
}
public static byte[] lcl_toByteArray(Objectobj)
{
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray ();
oos.close();
bos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return bytes;
}
}