IO流-檔案拷貝

風痕影默發表於2014-09-27

其實檔案的拷貝還是檔案讀取寫入的應用,實際是讀取此路徑上的檔案,然後寫入到指定路徑下的檔案。

程式碼舉例:

import java.io.*;
import java.lang.*;
class Test
{
    public static void main(String[] args)
    {
        copy("C:\\log.txt", "d:\\log.txt");
    }
    //塊讀取方式
    public static void copy(String sourcePath, String destPath)
    {
        final int READCACHELEN = 1024;
        try(FileReader fileReader = new FileReader(sourcePath))
        {
            int readReturnNum = 0;
            char[] readCache = new char[READCACHELEN];
            try(FileWriter fileWriter = new FileWriter(destPath, true))//定義新增為真
            {
                while((readReturnNum = fileReader.read(readCache)) != -1)
                {
                    fileWriter.write(readCache, 0, readReturnNum);
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
       System.out.println("transport Ok!");
    }
    //單個字元讀取方式
    public static void copy(String sourcePath, String destPath)
    {
        final int READCACHELEN = 1024;
        try(FileReader fileReader = new FileReader(sourcePath))
        {
            int readReturnNum = 0;
            try(FileWriter fileWriter = new FileWriter(destPath, true))
            {
                while((readReturnNum = fileReader.read()) != -1)//read讀取單個字元以整型返回
                {
                    fileWriter.write(readReturnNum);
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
       System.out.println("transport Ok!");
    }
}

 

相關文章