关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

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

发布时间:2020-03-16 00:00:00
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 {
    @Testpublic 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();
                }
            }
        }
    }
}

 


/template/Home/Zkeys/PC/Static