import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.jfree.util.Log;
/**
* Object 对象必须是可序列化对象 。 可序列化的 Object 对象都可以转换为一个磁盘文件;反过来则不一定成立,只有序列化文件才可以转换为
* Object 对象。
*
* @author fdc
*
*/
public class FileByteConvert {
public static byte[] fileToByteConvert(File imgFile) {
FileInputStream fis = null;
byte[] pData = new byte[(int) imgFile.length()];
try {
fis = new FileInputStream(imgFile);
fis.read(pData);
} catch (FileNotFoundException e) {
Log.info("文件没找到!" + e.getMessage());
} catch (IOException e) {
Log.info("读取文件出错!" + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
Log.info("关闭文件输入流出错!" + e.getMessage());
}
}
}
return pData;
}
public static File byteToFileConvert(byte[] byteArr, String outputFile) {
BufferedOutputStream stream = null;
File file = null;
try {
file = new File(outputFile);
FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(byteArr);
} catch (Exception e) {
Log.info("输出文件出错!" + e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.info("关闭文件输出流出错!" + e.getMessage());
}
}
}
return file;
}
public static Object byteToObjectConvert(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();
}
public static byte[] objectToBytesConvert(Serializable obj) throws Exception {
if (obj == null) {
return null;
}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
return bo.toByteArray();
}
}
File与byte[],Object互转
最新推荐文章于 2023-02-07 11:10:36 发布