package com.itheima;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 使用带缓冲功能的字节流复制文件。
*/
public class Test6
{
public static void main(String[] args) {
// TODO Auto-generated method stub
copyFile();
}
public static void copyFile(){
// 变量声明
File fileSourse = null;
File fileTarget = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
// 拷贝源文件读取
fileSourse = new File("d:/test.txt");
fis = new FileInputStream(fileSourse);
bis = new BufferedInputStream(fis);
// 拷贝目标文件
fileTarget = new File("d:/testTarge.txt");
fos = new FileOutputStream(fileTarget);
bos = new BufferedOutputStream(fos);
int inputByte = 0;
while((inputByte = bis.read()) != -1){
// 目标文件写入
bos.write(inputByte);
}
} catch (FileNotFoundException e1) {
System.out.println("拷贝源文件不存在");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if(bos != null){
// 流关闭
//(!!!!!!!!!!!!试验此处不关闭的效果!!!!!!!!!)
bos.close();
}
if(fos != null){
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("写入关闭失败");
}
try {
if(bis != null){
bis.close();
}
if(fis != null){
fis.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("读取关闭失败");
}
}
}
}
|
|