第一種方式:逐個字符進行讀寫操做(代碼註釋以及詳細內容空閒補充)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("讀寫失敗"); } } } } }