回顾BufferedInputStream-int read(byte[] buffer)BufferedOutputStream-void write(byte[] buff ,int offset

学习java基础,是一个反复学习的过程。
今天回顾BufferedInputStream int read(byte[] buffer) BufferedOutputStreamvoid write(byte[] buff ,int offset ,int len)

int read(byte[] buffer)
参数:
buff,字符流,将字符传入到字符数组当中。一般大小为1k,也就是1024*2byte
返回值:
int类型,读入缓冲区的总字节数,如果因为读到流的末尾而不再有数据可用,则返回-1。

write(byte[] buff ,int offset ,int len)
参数:
buff,从该缓冲区读取数据写入BufferedOutputStream中。
offset,从buff的offset位置读取。
len,要写入的字节数。


使用file.renameTo(File newFile)时
前提是操作file的流需要被关闭。


package com.lxh.iterview;
import java.io.*;
public class Copyavi {
	
	/**
	 * 将C盘中的avi文件,拷贝到D盘中,提高效率。
	 * 
	 * 思路:
	 * avi文件,是一个字节文件,应当使用字节流。
	 * */
	
	public static void main(String[] args) {
		File c = new File
			("c:\\avi\\黑马程序员_毕向东_Java基础视频教程第09天-10-面向对象(throw和throws的区别).avi");
		// 创建复制到D盘中的目录。
		File p = new File("d:\\avi");
		if(!p.exists()) 
			// 当该文件夹不存在时,直接将文件写入该文件夹下的文件中,则会发生FileNotFountException
			p.mkdir();
		File d = new File(p,"黑马程序员_毕向东_Java基础视频教程第09天-10-面向对象(throw和throws的区别).avi");
		
		BufferedInputStream bufin = null;
		BufferedOutputStream bufout = null;
		try {
			bufin = new BufferedInputStream(new FileInputStream(c));
			bufout = new BufferedOutputStream(new FileOutputStream(d));
			// 缓冲字节流,是将字节读取到字节数组缓冲区中,一般定义缓冲区的大小为1k
			byte[] buff = new byte[1024*2];
			// read(byte[])方法,返回读入缓冲区的总字节数
			int len = 0;
			// while方法循环读取,读取完毕时,返回-1,此时结束程序。
			while((len = bufin.read(buff)) != -1) {
				// write(byte[] b , offset , len)将buff中的数据,从offset开始的,len个字节存入到指定文件当中
				bufout.write(buff, 0, len);
				// flush功能可以讲缓冲区内的数据存入到文件中
				bufout.flush();
			}
			
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			try {
				bufin.close();
			} catch(IOException e) {
				e.printStackTrace();
			}
			try {
				bufout.close();
			} catch(IOException e) {
				e.printStackTrace();
			}
			// 当我将流调用的系统资源关闭后,再重命名该文件,成功了!
			File newf = new File(p,"newname.avi");
			d.renameTo(newf);
		}
	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值