BufferedCopy拷贝
利用BufferedReader 和 BufferedWriter 实现copy ,代码如下:
(未运行验证)
public class BufferedCopy_{
public static void main(String[] args) {
//说明:
//BufferedReader 和 BufferedWriter 是按照字符操作
//不要去操作二进制文件[声音,视频,doc,pdf等等],可能造成文件损坏
String srcFilePath = "e:\\a.java";
String destFilePath = "e:\\a.java";
BufferedReader br = null;
BufferedWriter bw = null;
String line;
try { //5.20
br = new BufferedReader(new FileReader(srcFilePath ));
bw = new BufferedWriter (new FileWriter(destFilePath ));
//说明 readLine 读取一行内容,但是没有换行
while ((line = br.readLine()) != null) {
//每读一行,就写入
bw.write(line);
//插入一个换行
bw.newLine();
}
} catch (IOEception e) {
e.printStackTrace();
} finally {
//关闭流
try {
if(br != null) {
br.close();
}
if(bw != null) {
bw.close();
}
} catch(IOEception e) {
e.printStackTrace();
}
}
}
}
处理流BufferedInputStream和BufferedOutputStream(处理二进制文件,例如视频图片等)
BufferedInputStream
BufferedInputStream是字节流,在创建 BufferedInputStream时,会创建一个内部缓冲区数组
BufferedInputStream类继承关系图
BufferedOutputStream
BufferedOutputStream是字节流,实现缓冲的输出流,可以将多个字节写入底层的输出流中,而不必对每次字节写入调用底层系统
BufferedOutputStream类继承关系图
字节处理流拷贝文件
字节处理流拷贝文件代码
//使用BufferedInputStream和BufferedOutputStream可以完成二进制拷贝
//思考:字节流可以操作二进制文件,那么他们可以操作文本文件吗? 可以
public class BufferedCopy2{
public static void main(String[] args) {
String srcFilePath = "e:\\Kaola.jpg";
String destFilePath = "e:\\CopyKaola.jpg";
//创建BufferedOutputStream对象和BufferedInputStream对象
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//因为FileInputStream 是 InputStream 子类
bis = new BufferedInputStream (new FileInputStream(srcFilePath ));
bos = new BufferedOutputStream (new FileOutputStream(destFilePath ));
//循环的读取文件,并写入到destFilePath
byte[] buff = new byte[1024]
int readLen = 0;
//当返回-1时,就表示文件读取完毕
while((readLen = bis.read(buff)) != -1 ){
bos.write(buff, 0 ,readLen);
}
System.out.println("文件拷贝完毕~~~");
} catch (IOEception e) {
e.printStackTrace();
} finally {
//关闭流,关闭外层处理流即可,底层会去关闭的节点流
try {
if(bis != null) {
br.close();
}
if(bw != null) {
bos.close();
}
} catch(IOEception e) {
e.printStackTrace();
}
}
}
}