import java.io.*;
class BbCopy
{
/*
使用缓冲区的输入输出流对象来复制数据
*/
public static void main(String[] args)
{
final File file=new File("d:/temp.txt");
//在子线程中复制数据
new Thread(){
@Override
public void run(){
try{
System.out.println("文件正在复制");
Thread.sleep(3000);
copyfile(file);
}catch(Exception e){
throw new RuntimeException("复制未成功");
}finally{
System.out.println("文件复制成功");
}
}
}.start();
}
public static void copyfile(File sFile){
Reader fr=null;
Writer fw=null;
BufferedReader br=null;
BufferedWriter bw=null;
try{
//先获取源文件的路径
String sPath=sFile.getPath(); //该方法得到的是文件的绝对路径
//组拼目标路径为了程序的兼容性我们使用文件分割符对象
// \就是文件分割符
String dPath="e:"+File.separator+sPath.substring(sPath.lastIndexOf(File.separator)+1);
File dFile=new File(dPath);
fr=new FileReader(sFile);
fw=new FileWriter(dFile);
br=new BufferedReader(fr);
bw=new BufferedWriter(fw);
//因为buffered内部封装了缓冲区。所以我们就不需要再创建数组做为缓冲区了
String str=null; //用于记录住读取到的数据。我们使用的是读取一行的操作
while((str=br.readLine())!=null){ //如果没有读取到文件末尾
//readLine返回的是一行中换行符之前的内容
bw.write(str); //将缓存中的数据写入到输出流中
bw.newLine(); //换行
bw.flush(); //刷新数据
}
}catch(Exception e){
throw new RuntimeException("出现错误了");
}finally{
try{
if(bw!=null){
bw.close(); // 关闭BufferedWriter
}
if(br!=null){
br.close(); //关闭BufferedReader
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
《黑马程序员》 Buffered缓冲区练习之基于子线程的文件复制
最新推荐文章于 2021-01-29 15:34:12 发布