`

File与byte[],Object互转

 
阅读更多
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();
	}
}
分享到:
评论

相关推荐

    java对象转成byte数组的3种方法

    主要为大家详细介绍了java对象转成byte数组的3种方法,具有一定的参考价值,感兴趣的朋友可以参考一下

    自己写的DES加密解密 ASP.NET(C#)

    { private static byte[] Key64 = { 42, 16, 93, 156, 78, 4, 218, 32 }; private static byte[] IV64 = { 55, 103, 246, 79, 36, 99, 167, 3 }; protected void Page_Load(object sender, EventArgs e) { } ...

    a_byte_of_python

    it was written by Swaroop C H.its name is "a byte of python". Table of Contents Preface Who This Book Is For History Lesson Status of the book Official Website License Terms Using the ...

    文件加密解密算法(Java源码)

    byte[] rawKeyData = Util.readFile(keyfile); // 从原始密钥数据创建DESKeySpec对象 Class classkeyspec=Class.forName(Util.getValue("keyspec")); Constructor constructor = classkeyspec.getConstructor(new...

    IsoBuster Pro 2.3.0.1 - Final

    * Show GMT Offset when date-time is known for an IFO file object * Auto-recognition support for 2056 byte / block image files * Added IsoBuster path to DOS box PATH variable * SectorView via the ...

    二进制读取.asmx.cs

    byte[] rbyte = myBinRdr.ReadBytes(Convert.ToInt32(rs["FileBegin"].ToString())); rbyte = myBinRdr.ReadBytes(Convert.ToInt32(rs["FileLength"].ToString())); this_list.Add((object)rbyte); this_list....

    java压缩文件源码--ZipUtils

    Object[] fileArray = allFiles.toArray(); BufferedInputStream in = null; FileInputStream fis = null; ZipOutputStream zos = null; FileOutputStream fos = null; try { fos = new ...

    大名鼎鼎SWFUpload- Flash+JS 上传

     SWFUpload是一个客户端文件上传工具,最初由Vinterwebb.se开发,它通过整合Flash与JavaScript技术为WEB开发者提供了一个具有丰富功能继而超越传统<input type="file" />标签的文件上传模式。 [编辑本段]SWFUpload...

    网页无组件上传图片与大家分享

    private String[] sourceFile = new String[255]; //源文件名 private String[] suffix = new String[255]; //文件后缀名 private String canSuffix = ".gif.jpg.jpeg.png"; //可上传的文件后缀名 private String...

    asp.net 文件夸域名传输带进度条

    FileStream fs = new FileStream(this.fileUpload.PostedFile.FileName, FileMode.Open, FileAccess.Read); ms = new BinaryReader(fs); string newFile = DateTime.Now.Ticks.ToString(); string exit = this....

    C# 黑马.Net_大文件拷贝实例源码

    private void button4_Click(object sender, EventArgs e) { this.progressBar1.Value = 0; this.label1.Text = "0%"; if (!File.Exists(this.textBox1.Text)) { MessageBox.Show("找不到目标文件!"); ...

    阿里云ossandroid端

    public void onProgress(String objectKey, int byteCount, int totalSize) { Log.d(TAG, "[onProgress] - current upload " + objectKey + " bytes: " + byteCount + " in total: " +...

    pyfsig:python 文件签名标识符 - 使用它从文件头中识别文件

    # returns Match object (list of signatures) that match the file at this file path herp = get_from_path ( f_name ) # this can be a string or a bytestring, will raise exception if no matchi

    android好用的框架(封装了数据库,注解,网络,图片缓存的框架)

    有时间将会扩展JSONObject,xmlDom,byte[],bitmap等): public HttpClient getHttpClient() public HttpContext getHttpContext() public void configCookieStore(CookieStore cookieStore) //配置cookie ...

    c# 加密和解密相关代码

    数据的加密与解密 文件的加密与解密 第 章 加密与解密技术 第19章 加密与解密技术 829 19.1 数据的加密与解密 实例571 异或算法对数字进行加密与解密 光盘位置:光盘\MR\19\571 中级 趣味指数: 实 例说明 在实现...

    log4net .net日志打印源代码 支持win32或wm

    public void WriteBytes(LOG_LEVEL logLevel, string title, int len, byte[] lpBytes) { } #endregion #region ------Private------ private void OpenFile() { } private void CheckFileSize() { }...

    Socket Python示例

    fromfd() -- create a socket object from an open file descriptor [*] fromshare() -- create a socket object from data received from socket.share() [*] gethostname() -- return the current hostname ...

    [Mastering.Node.js(2013.11) 精通Node.js

    Reading byte by byte 106 fs.read(fd, buffer, offset, length, position, callback) 106 Fetching an entire file at once 107 fs.readFile(path, [options], callback) 107 Creating a readable stream 107 fs....

    IO输入输出留

    1 File f=new File("d:/abc") (d:\\abc) 2 File f=new File ("目录","文件名") 创建一个 File 封装对象 可以不存在 方法 -------------------------------------------- 文件、目录属性方法 文件、目录属性 ...

Global site tag (gtag.js) - Google Analytics