Java使用缓冲流实现文本文件的copy
程序员文章站
2024-01-17 12:15:58
package com.io.buffered; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import ja ......
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(); } } } } }
上一篇: C++ 虚继承