zoukankan      html  css  js  c++  java
  • Java字符流读写数据的两种方式

    第一种方式:逐个字符进行读写操作(代码注释以及详细内容空闲补充)

    package IODemo;
    
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class CopyFileDemo {
    
     /**
      * @param args
      * @throws IOException 
      */
     public static void main(String[] args) throws IOException {
    
      FileReader fr=new FileReader("Demo.txt");
      
      FileWriter fw=new FileWriter("Demo1.txt");
      int ch=0;
      while((ch=fr.read())!=-1){//单个字符进行读取
       fw.write(ch);//单个字符进行写入操作
      }
      fw.close();
      fr.close();
     }
    
    }
    
     

    第二种方式:自定义缓冲区,使用read(char buf[])方法,此方法较为高效

     
    package IODemo;
    
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class CopyFileDemo2 {
    
     private static final int BUFFER_SIZE = 1024;
    
     /**
      * @param args
      */
     public static void main(String[] args) {
    
      FileReader fr = null;
      FileWriter fw = null;
      try {
       fr = new FileReader("Demo.txt");//工程所在目录
       fw = new FileWriter("Demo2.txt");
       char buf[] = new char[BUFFER_SIZE];
       int len = 0;
       while ((len = fr.read(buf)) != -1) {
        fw.write(buf, 0, len);
       }
      } catch (Exception e) {
       // TODO: handle exception
      } finally {
       if (fr != null) {
        try {
         fr.close();
        } catch (IOException e) {
         System.out.println("读写失败");
        }
       }
       if (fw != null) {
        try {
         fw.close();
        } catch (IOException e) {
         System.out.println("读写失败");
        }
       }
      }
    
     }
    
    }
  • 相关阅读:
    toggle()
    !important
    js 实现向下滑动页面时遇顶固定
    layui多文件选择之后自动上传
    position:fixed和z-index:1
    转:jquery 智能浮动定位smartFloat
    转:DATA URL简介及DATA URL的利弊
    年,月 ,季节 下拉框
    左连接与右连接,外连接与内连接
    git 恢复删去的东西, 以及在本地建个仓库,让远程也有这个仓库
  • 原文地址:https://www.cnblogs.com/ysw-go/p/5280792.html
Copyright © 2011-2022 走看看