Java NIO 之 複製檔案 案例

來源:互聯網
上載者:User

標籤:java   filechannel   bytebuffer   


需求:實現檔案的copy


練習目的:

  1.  瞭解JavaNIO知識,主要是關注一下FileInputStream,FileChannel,FileOutputStream,ByteBuffer 之間的關係

  2. 瞭解如何擷取FileChannel

public class CopyFile {    public static void main(String[] args) throws Exception {        String inFile = "gitHub.txt";        String outFile = "gitHub2.txt";                //擷取源檔案和目標檔案的輸入資料流、輸出資料流        FileInputStream fin = new FileInputStream(inFile);        FileOutputStream fout = new FileOutputStream(outFile);                //擷取輸入、輸出通道        FileChannel fcin = fin.getChannel();        FileChannel fcout = fout.getChannel();                //建立緩衝區        ByteBuffer buffer = ByteBuffer.allocate(1024);                while (true) {                    //清楚緩衝區的資料,可以接收新的資料            buffer.clear();                    //從輸入通道中將資料讀到緩衝區            int r = fcin.read(buffer);                    //read方法返回讀取的位元組數,可能為0, 如果該通道已經達到流的末尾,則返回-1            if (r == -1) {                break;            }                    //flip方法,讓緩衝區可以將新讀入的資料寫入另一個通道            buffer.flip();                    //從緩衝區 將資料寫到 輸出通道裡            fcout.write(buffer);        }                //最後關閉        fcin.close();        fout.close();    }}


總結如下:

  1. 資料的流向:

   650) this.width=650;" src="https://s1.51cto.com/wyfs02/M00/A6/10/wKioL1nIoFzhzlyJAAAtTtCepXQ467.png" title="001.png" alt="wKioL1nIoFzhzlyJAAAtTtCepXQ467.png" />

  1. 什麼時候調用FileChannel的read,write方法?

   根據資料的方向來確定

   650) this.width=650;" src="https://s5.51cto.com/wyfs02/M00/A6/10/wKioL1nIoRqjzAD7AABkbNmoa2E915.png" title="002.png" alt="wKioL1nIoRqjzAD7AABkbNmoa2E915.png" />  







   

   







本文出自 “XEJ分布式工作室” 部落格,請務必保留此出處http://xingej.blog.51cto.com/7912529/1968417

Java NIO 之 複製檔案 案例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.