欢迎光临散文网 会员登陆 & 注册

使用字符缓冲流实现文件的拷贝

2020-04-02 15:06 作者:小垃圾kiki  | 我要投稿
package cn.jd.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class CopyTxt {
    public static void main(String[] args) {
        copy("1.txt","2.txt");
    }
    
    //这里是对拷贝方法进行了封装,还没有对流进行封装     我们使用的是字符缓冲流,别看错是使用成了字节
    public static void copy(String srcPath,String destPath) {
        //确定源
        File src=new File(srcPath);//读取的文件,使用输入流    因为是从文件到程序
        File src1=new File(destPath);//写入文件,输出流,从程序到文件
        //确定流
        BufferedReader is=null;
        BufferedWriter os=null;
        try {
             is=new BufferedReader(new FileReader(src));
             os=new BufferedWriter(new FileWriter(src1));
            //定义一个字符串对象来存储文件里面的字符串
             String line=null;
            //确定方法
            while((line=is.readLine())!=null) {   //通过is.read读取字节数组的长度
//                os.append("世界和平");
                os.write(line);
                os.newLine();//回车加换行
            }
            os.flush();   //刷新缓冲流
            
        } catch (FileNotFoundException e) {
            
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                if(os!=null) {
                    os.close();  //先关闭输出流
                }
                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                if(is!=null) {
                    is.close();  
                }
                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

    
    
}

使用字符缓冲流实现文件的拷贝的评论 (共 条)

分享到微博请遵守国家法律