字節流對文件的操作更多適用於文件複製和傳送,而字符流則注重於文件的讀取分析操作

1:代碼如下

public class IO {

    public static void main(String[] args) throws IOException {
        doReaderorWriter();
    }

    /**
     * 這是字節流的測試,操作不方便,不能像字符流那樣子一行一行的操作,而且一般需要藉助byte[]
     */
    public static void doStream() throws IOException{
        File fileinput = new File("C:/Users/Kin.Liufu/Desktop/一點小心得/changeNote.txt");
        if(!fileinput.exists()){
            System.out.println("你選擇的文件不存在");
        }
        @SuppressWarnings("resource")
        FileInputStream fileInputStream = new FileInputStream(fileinput);

        byte[] bt = new byte[fileInputStream.available()]; 
        fileInputStream.read(bt);

        File fileoutput = new File("C:/Users/Kin.Liufu/Desktop/一點小心得/複製/" + fileinput.getName());
        File fileParent = new File(fileoutput.getParent());
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        @SuppressWarnings("resource")
        //這裏的true表示在文章最後追加數據,而不刪除原本的數據
        FileOutputStream fileOutputStream = new FileOutputStream(fileoutput,true);
        fileOutputStream.write(bt);
        System.out.println(bt.length);
    }

    /**
     *  這是字符流的測試,能一行一行的讀取數據,便於分析,而且一般不需要藉助byte[]
     */
    public static void doReaderorWriter() throws IOException{
        FileReader fileReader = new FileReader("C:/Users/Kin.Liufu/Desktop/一點小心得/changeNote.txt");

        //這裏的true表示在文章最後追加數據,而不刪除原本的數據
        FileWriter fileWriter = new FileWriter("C:/Users/Kin.Liufu/Desktop/一點小心得/複製/abc.txt",true);

        BufferedReader bt = new BufferedReader(fileReader);
        PrintWriter printWriter = new PrintWriter(fileWriter);
        String stringtemp = null;
        while((stringtemp = bt.readLine()) != null){
            printWriter.write(stringtemp);
            printWriter.flush();
            System.out.println(stringtemp);
        }

        System.out.println();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章