1. 程式人生 > 實用技巧 >使用FileInputStream 和 FileOutputStream 進行copy流 和 使用FileReader 和 FileWriter 進行 copy流案例:

使用FileInputStream 和 FileOutputStream 進行copy流 和 使用FileReader 和 FileWriter 進行 copy流案例:

使用FileInputStream和FileOutputStream進行copy流案例:

package com.javaSe.Copy;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/*
使用FileInputStream + FileOutputStream完成檔案的拷貝
拷貝的過程應該是一邊讀,一邊寫。
使用以上的位元組流拷貝檔案的時候,檔案型別隨意寫,萬能的。什麼樣的檔案都能拷貝
*/ public class CopyTest01 { public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; try { // 建立一個輸入流物件 fis = new FileInputStream("F:\\略略略\\1\\137349.mp4"); // 建立一個輸出流物件 fos = new
FileOutputStream("H:\\137349.mp4"); // 最核心的:一邊讀一邊寫 byte[] bytes = new byte[1024 * 1024]; // 1MB(一次最多拷貝1MB) int readCount = 0; while ((readCount = fis.read()) != -1){ fos.write(bytes,0,readCount); } fos.flush(); }
catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 分開try 不要一起try // 一起try的時候,其中一個出現異常,可能會影響到另一個流的關閉。 if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }

使用FileReader和FileWriter進行copy流案例:
package com.javaSe.Copy;


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


/*
使用FileReader 和 FileWriter 進行拷貝的話,只能拷貝普通文字檔案。
*/
public class CopyTest02 {
    public static void main(String[] args) {
        FileReader fr = null;
        FileWriter fw = null;
    
        try {
            //
            fr = new FileReader("Stream\\src\\com\\javaSe\\Copy\\CopyTest02.java");
            //
            fw = new FileWriter("CopyTest02.java");
            
            // 一邊讀、 一邊寫
            char[] chars = new char[1024 * 1024];// 1MB
            int readCount = 0;
            while ((readCount = fr.read(chars)) != -1){
                fw.write(chars,0,readCount);
            }
            
            // 重新整理
            fw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
}