1. 程式人生 > >IO(字元流——複製文字檔案)

IO(字元流——複製文字檔案)

IO(字元流——複製文字檔案)

方法一

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by Mr.Li on 2017/6/1.
 */

//需求:將f盤的一個文字檔案複製到d盤。
    /*
    1;需要讀取源
    2:將讀到的資料寫入目的地
    3:既然是操作文字檔案,使用字元流
     */
public class CopyTextTest {
    public static void main(String []args)
throws IOException { //1,讀取一個已有的文字檔案沒使用字元讀取流和檔案相關聯 FileReader fr=new FileReader("hhh.txt"); //2建立一個目錄,用於儲存讀到的資料 FileWriter fw=new FileWriter("nnn.txt"); //3:頻繁的讀學操作 int ch=0; while ((ch=fr.read())!=-1) { fw.write(ch); }
//4:關閉流資源 fw.close(); fr.close(); } } //Exception in thread "main" java.io.FileNotFoundException: 000.txt (系統找不到指定的檔案。) //因為這個檔案必須建立在Java大檔案中,否則讀取不到


方法二
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by Mr.Li on 2017/6/2.
 */

public class 
CopyTextTest1 { private static final int BUFFER_SIZE=1024; public static void main(String[] args) throws IOException { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("hhh.txt"); fw = new FileWriter("nnn.txt"); //建立一個臨時容器,用於快取讀取到的字元。 char[] buf = new char[BUFFER_SIZE]; //定義一個變數記錄讀取到的字元(其實就是往數組裡裝的字元個數) int len = 0; while ((len = fr.read(buf)) != -1) { fw.write(buf, 0, len); } } catch (Exception e) { //System.out.println("讀寫失敗"); throw new RuntimeException("讀寫失敗"); } finally { if (fw != null) try { fw.close(); } catch (IOException e) { e.printStackTrace(); } if (fr != null) try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }


就while語句迴圈次數來講:方法2 效率更高