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[])方法,此方法较为高效spa

 
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("读写失败"); } } } } }
相关文章
相关标签/搜索