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();
                }
            }
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM