我们在之前的装饰者设计模式中,我们学到了,包装类BufferedReader和BufferedWriter是用于修饰节点流的。让我们处理节点流能够有更强的功能。
下面演示BufferReader和Writer的基本用法。
package IO流.Buffered; import java.io.*; /** * @program:多线程和IO * @descripton: * @author:ZhengCheng * @create:2021/10/5-17:35 **/ public class BufferedDemo02 { public static void main(String[] args) { BufferedWriter bw = null; BufferedReader br = null; try { bw = new BufferedWriter(new FileWriter("d:\\new1.txt", true)); br = new BufferedReader(new FileReader("d:\\new1.txt")); String readstr; String writestr = "Hello,JVM"; bw.newLine(); bw.write(writestr); bw.flush(); while ((readstr = br.readLine())!=null){ System.out.println(readstr); } } catch (IOException e) { e.printStackTrace(); } finally { try { bw.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* public void close() throws IOException { synchronized (lock) { if (in == null) return; try { in.close(); } finally { in = null; cb = null; } } } */
不难看到,我们在关闭包装流时,只需要对包装流关闭,查看源码我们能发现,close方法中,自动帮我们关闭了节点流。这个in指得就是节点流。
下面使用BufferedReader和Writer进行复制操作。但是注意,不要去操作二进制文件(声音,视频,doc,pdf等)可能会造成文件损坏。如何操作二进制文件呢?使用我们的BufferedInputStream和BufferedOutputStream。
package IO流.Buffered; import java.io.*; /** * @program:多线程和IO * @descripton: * @author:ZhengCheng * @create:2021/10/5-17:42 **/ public class BufferedCopy { public static void main(String[] args) { String fpath ="d:\\new1.txt"; String tpath ="d:\\new3.txt"; new BufferedCopy().bufferedCopy(fpath,tpath); } public void bufferedCopy(String frompath ,String topath){ BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(frompath)); bw = new BufferedWriter(new FileWriter(topath)); String tempStr ; while ((tempStr = br.readLine())!=null){ bw.write(tempStr); bw.newLine(); bw.flush(); } }catch (IOException e){ e.printStackTrace(); }finally { try { br.close(); bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
使用BufferedInputStream和BufferedOutputStream操作二进制文件。
package IO流.Buffered; import java.io.*; /** * @program:多线程和IO * @descripton: * @author:ZhengCheng * @create:2021/10/5-17:58 **/ public class BufferedCopy2 { public static void main(String[] args) { String fpath ="d:\\a1.jpg"; String tpath ="d:\\a2.jpg"; new BufferedCopy2().bufferedCopy(fpath,tpath); } public void bufferedCopy(String frompath ,String topath){ BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(new FileInputStream(frompath)); bos = new BufferedOutputStream(new FileOutputStream(topath)); int readlen = 0; byte[] buff = new byte[1024]; while ((readlen = bis.read(buff))!=-1){ bos.write(buff,0,readlen); } }catch (IOException e){ e.printStackTrace(); }finally { try { bis.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } } }