JAVA代码实现文本文件复制模板

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyText {
    public static void main(String[] args) {
        //原路径
        String oldFile = "";
        //新路径
        String newFile = "";
        //调用拷贝字符文件的方法
        copyText(oldFile,newFile);
    }
    //定义一个拷贝字符文件的方法,oldFile-->原路径 newFile-->新路径
    public static void copyText(String oldFile,String newFile) {
        //声明字符输入缓冲流对象
        BufferedReader br = null;
        //声明字符输出缓冲流对象
        BufferedWriter bw = null;
        try {
            //创建字符输入缓冲流对象
            br = new BufferedReader(new FileReader(new File(oldFile)));
            //创建字符输出缓冲流对象
            bw = new BufferedWriter(new FileWriter(new File(newFile)));
            //复制,一边读一边写
            char[] ch = new char[1024];
            int len;
            while((len = br.read(ch)) != -1) {
                bw.write(ch, 0, len);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/private-mingmie/p/11818979.html