首页 > 编程语言 > 详细

Java使用缓冲流实现文本文件的copy

时间:2020-03-15 23:37:18      阅读:84      评论:0      收藏:0      [点我收藏+]
package com.io.buffered;

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

import org.junit.Test;

/**
 * 使用缓冲流实现文本文件的copy
 * 
 */
public class BufferedStreamFileText {
    @Test
    public void copyTestTextTest() {
        // 记录耗时
        long start = System.currentTimeMillis();
        String src = "./hello.txt";
        String dest = "./world.txt";
        copyTestText(src, dest);
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start));
    }

    @SuppressWarnings("resource")
    public static void copyTestText(String src, String dest) {
        // 3、创建FileWriter 
        FileWriter fw = null;
        // 4、创建BufferedWriter 用于包装节点流,提高效率
        BufferedWriter bw = null;
        try {
            // 1、创建FileReader 
            FileReader fr = new FileReader(src);
            // 2、创建BufferedReader 用于包装节点流,提高效率
            BufferedReader br = new BufferedReader(fr);

            fw = new FileWriter(dest);
            bw = new BufferedWriter(fw);
            // 5、读取指定文件内容
            String str = null;
            while ((str = br.readLine()) != null) {
                // 6、将读取的内容写到目标地点
                bw.write(str + "\n");//读取文件换行
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 7、关闭流
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

Java使用缓冲流实现文本文件的copy

原文:https://www.cnblogs.com/yonxin/p/12500801.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!