首頁技術(shù)文章正文

FileChannel如何讀寫文件?

更新時間:2023-03-27 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

獲取FileChannel不能直接打開,必須通過 FileInputStream、FileOutputStream 或者 RandomAccessFile 來獲取 FileChannel,它們都有 getChannel 方法。

  通過FileInputStream獲取的channel只能讀

  通過FileOutputStream獲取的channel只能寫

  通過RandomAccessFile是否能讀寫根據(jù)構(gòu)造RandomAccessFile 時的讀寫模式?jīng)Q定。

1.讀取

會從channel讀取數(shù)據(jù)填充ByteBuffer,返回值表示讀到了多少字節(jié),-1 表示到達(dá)了文件的末尾。

int readBytes = channel.read(buffer);

2.寫入

寫入的正確代碼如下:

ByteBuffer buffer = ...;
buffer.put(...); // 存入數(shù)據(jù)
buffer.flip();   // 切換讀模式

while(buffer.hasRemaining()) {
    channel.write(buffer);
}

在 while 中調(diào)用 channel.write 是因為 write 方法并不能保證一次將 buffer 中的內(nèi)容全部寫入 channel

3.關(guān)閉

channel 必須關(guān)閉,不過調(diào)用了 FileInputStream、FileOutputStream 或者 RandomAccessFile 的 close 方法會間接地調(diào)用 channel 的 close 方法。

4.位置

獲取當(dāng)前位置的示例代碼如下:

long pos = channel.position();

設(shè)置當(dāng)前位置

long newPos = ...;
channel.position(newPos);

設(shè)置當(dāng)前位置時,如果設(shè)置為文件的末尾會讀取會返回 -1 。這時寫入,會追加內(nèi)容,但要注意如果 position 超過了文件末尾,再寫入時在新內(nèi)容和原末尾之間會有空洞(00)。

5.大小

使用 size 方法獲取文件的大小

6.強制寫入

操作系統(tǒng)出于性能的考慮,會將數(shù)據(jù)緩存,不是立刻寫入磁盤??梢哉{(diào)用 force(true) 方法將文件內(nèi)容和元數(shù)據(jù)(文件的權(quán)限等信息)立刻寫入磁盤。





分享到:
在線咨詢 我要報名
和我們在線交談!