Java File和byte数据之间的转换

package cn.iworker.file;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileTest
{
	
	public static void main(String[] args)
	{
		file2BetyArray();
		fileToBetyArray();
		BetyToFile("D:\\Study\\Java\\First.class");
	}

	public static byte[] file2BetyArray()
	{
		File file = new File("D:\\Study\\Java\\First.class");
		if (!file.exists()) {
			return null;
		}
		FileInputStream stream = null;
		ByteArrayOutputStream out = null;
		try {
			stream = new FileInputStream(file);
			out = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = stream.read(b)) != -1) {
				out.write(b, 0, n);
			}
			return out.toByteArray();// 此方法大文件OutOfMemory
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				stream.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return null;
	}

	public static byte[] fileToBetyArray()
	{
		FileInputStream fileInputStream = null;
		File file = new File("D:\\Study\\Java\\First.class");
		byte[] bFile = null;
		try {
			bFile = new byte[(int) file.length()];
			fileInputStream = new FileInputStream(file);
			fileInputStream.read(bFile);
			fileInputStream.close();
			for (int i = 0; i < bFile.length; i++) {
				System.out.print((char) bFile[i]);
			}
			System.out.println("Done");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fileInputStream.close();
				bFile.clone();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bFile;
	}

	public  static File BetyToFile( String filePath)
	{
		File file = new File(filePath);
		BufferedOutputStream stream = null;
		FileOutputStream fstream = null;
		byte[] data=new byte[(int)file.length()];
		try {
			fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (stream != null) {
					stream.close();
				}
				if (null != fstream) {
					fstream.close();
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return file;
	}

}

  • 25
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值