Java100-009:I/O流:利用文件输入流,文件输出流,字节数组输入流,字节数组输出流,来实现图片的拷贝

package java02;
/**
 *   我的java每天100行代码008
 * I/O流:利用文件输入流,文件输出流,字节数组输入流,字节数组输出流,来实现图片的拷贝
 * 
 * @author Administrator
 *
 */
import java.io.*;

//I/O流的常规操作步骤:创建源,选择流,操作(读与写),释放资源
//对于字节数组的操作可以没有创建源课释放资源两个部分,因为字节数组属于在虚拟机内部操作,由gc来负责资源回收
//需要知道I/O流中的四大抽象类,每一个抽象类中常规方法的使用
public class java0093 {
	public static void main(String[] args) {
		byte[] dates =fileToByteArray("3.jpg");//用变量表示方法的返回值
		System.out.println(dates.length);
		
		byteArrayToFile(dates,"5.jpg");
	}
	
	//图片读取到字节数组中
	//图片到程序,程序到字节数组
	public static byte[] fileToByteArray(String filePath) {
		//创建源,字节数组可以没有源头
		File src = new File(filePath);
		//选择流
		InputStream in =null;
		ByteArrayOutputStream baos = null;
		try {
			//操作
			in = new FileInputStream(src);
			baos = new ByteArrayOutputStream();
			byte[] flush = new byte[1024];//创建容器的方式
			int len = -1;
			while((len = in.read(flush))!=-1) {
				baos.write(flush,0,len);
			}
			baos.flush();
			return baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				//释放资源
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	//字节数组转换成图片
	//字节数组到程序,程序到图片
	public static void byteArrayToFile(byte[] dates,String s) {
		//创建源,字节数组可以没有源头
		File f = new File(s);
		//选择流
		ByteArrayInputStream ba = null;
		OutputStream out = null;
		
		try {
			ba = new ByteArrayInputStream(dates);
			out = new FileOutputStream(f);
			//操作
			byte[] b =new byte[1024];
			int l=-1;
			while((l=ba.read(b))!=-1) {
				out.write(b,0,l);
			}
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//释放资源,字节数组可以不用释放资源
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值