本文實例講述了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("讀寫失敗"); } } } }}更多關於java算法相關內容感興趣的讀者可查看本站專題:《Java文件與目錄操作技巧匯總》、《Java數據結構與算法教程》、《Java操作DOM節點技巧總結》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。