学习java基础,是一个反复学习的过程。
今天回顾BufferedInputStream的 int read(byte[] buffer) 和BufferedOutputStream的void 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);
}
}
}