import java.awt.image.BufferedImageFilter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;/**
* 用四种流实现文件的拷贝
* @author Administrator
**/
public classCopyFileTest {public static voidmain(String[] args) {//TODO Auto-generated method stub
String srcPath="d:/test.txt";
String destPath="f:/aaaa.txt";
copyFile(srcPath,destPath);//字节流实现文件的拷贝
copyFile2(srcPath,destPath);//字节缓冲流实现文件的拷贝
copyFile3(srcPath,destPath);//字符流实现文件的拷贝
copyFile4(srcPath,destPath);//字符缓冲流实现文件的拷贝
}/**
* 用字节流实现文件的拷贝
* @param scrPath 源路径名
* @param destPath 目标路径名*/
private static voidcopyFile(String srcPath, String destPath) {//TODO Auto-generated method stub
try (FileInputStream fis = newFileInputStream(srcPath);
FileOutputStream fos= newFileOutputStream(destPath);){//新建一个字节数组
byte[] b=new byte[1024];//声明一个整型常量,用来记录数组的长度
intlen;//文件的拷贝
while((len=fis.read(b))!=-1){
fos.write(b,0,len);
}
System.out.println("拷贝文件成功");
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}/**
* 字节缓冲流实现文件的拷贝
* @param scrPath 源路径名
* @param destPath 目标路径名*/
private static voidcopyFile2(String srcPath, String destPath) {//TODO Auto-generated method stub
try(BufferedInputStream bis = new BufferedInputStream(newFileInputStream(srcPath));
BufferedOutputStream bos= new BufferedOutputStream(newFileOutputStream(destPath));){//创建一个字节数组
byte[]b=new byte[1024];//int常量用来接收位置
intlen;//开始循环读取字节,写入文件
while((len=bis.read(b))!=-1){
bos.write(b,0,len);
}
System.out.println("文件拷贝成功");
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}/**
* 字符流实现文件的拷贝
* @param scrPath 源路径名
* @param destPath 目标路径名*/
private static voidcopyFile3(String srcPath, String destPath) {//TODO Auto-generated method stub
try (FileReader fr = newFileReader(srcPath);
FileWriter fw= newFileWriter(destPath);){//创建一个字符数组
char[] ch=new char[1024];//声明一个变量
intlen;while((len=fr.read(ch))!=-1){
fw.write(ch,0,len);
}
System.out.println("拷贝文件成功");
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}/**
* 字符缓冲流实现文件的拷贝
* @param srcPath 源路径名
* @param destPath 目标路径名*/
private static voidcopyFile4(String srcPath, String destPath) {//TODO Auto-generated method stub
try (BufferedReader br = new BufferedReader(newFileReader(srcPath));
BufferedWriter bw= new BufferedWriter(newFileWriter(destPath));){//字符缓冲是对文件一行读取
String temp; //临时变量记录文件读取的位置
while((temp=br.readLine())!=null){
bw.write(temp);
bw.newLine();//读取一行,并实现换行
}
System.out.println("文件拷贝成功");
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}