Java-字符流逐行读取/写入文件

    /**
     * 字符流,每次读取/写入一行
     * BufferedReader/PrintWriter
     * @Author: www.itze.cn
     * @Date: 2020/9/28 10:29
     * @Email: 814565718@qq.com
     * @param srcFile
     * @param destFile
     */
    public static void brAndpw(String srcFile,String destFile){
        try {
            BufferedReader reader = new BufferedReader(new FileReader(srcFile));
            //参数说明,第二个true时,写入的时候会自动刷新,就不需要刷新了
            PrintWriter writer = new PrintWriter(new FileOutputStream(destFile), true);
            String str = null;
            //读取,每次读取一行
            while ((str=reader.readLine())!=null){
                //写入,println:写入并自动换行,print:写入但是不执行换行
                writer.println(str);
            }
            reader.close();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

使用方法

    public static void main(String[] args) {
        String srcFile = "D:\\newCountry.txt";
        String destFile = "D:\\newCountry2.txt";
        brAndpw(srcFile,destFile);
    }

发表评论

邮箱地址不会被公开。 必填项已用*标注