關於JAVA中順序IO的基本操作


關於JAVA中順序IO的基本操作


寫在前面

最近研究一下JAVA中的順序IO,在網絡上找了一會兒,發現少有詳細的介紹,顧此在此處說說順序IO,才學疏淺,如有不對,望賜教。

什么是順序IO

事實上JAVA具有很多操作文件的方案(方法), 許多程序需要將一些事件記錄到本地存儲中,常見的如數據庫,MQ等,首先文件是許多帶數據的塊組成的,傳統IO操作文件具有一個尋址過程(事實上硬件上也會存在尋道,旋轉延遲等因素),小文件尚可,大文件就比較消耗性能和時間,比如數據庫分配的文件(本地),順序IO具備指定位置的功能,但是任然需要我們維護一個偏移量(游標).

MappedByteBuffer

JAVA順序IO通過MappedByteBuffer實現,與傳統IO不同的是,MappedByteBuffer需要使用者提供一個位置(偏移量),詳細看以下代碼:

mappedByteBuffer.position(index);
mappedByteBuffer.put(content.getBytes(StandardCharsets.UTF_8));

代碼中可見,通過MappedByteBuffer提供的api position();來指定位置(偏移量),put()進行寫操作,詳細如下。

寫操作

先看代碼:

public int write(File file ,String content ,int index,long size){
RandomAccessFile randomAccessFile;
MappedByteBuffer mappedByteBuffer;
try {

randomAccessFile = new RandomAccessFile(file,"rw"); //1
FileChannel fileChannel = randomAccessFile.getChannel(); //2
mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE,0,size); //3

mappedByteBuffer.position(index); //4
mappedByteBuffer.put(content.getBytes(StandardCharsets.UTF_8)); //5
return mappedByteBuffer.position(); //6
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
  • 上述代碼中標注1位置中使用RandomAccessFile (隨機流)來打開文件,此流與傳統IO除了兼並讀寫之外,在一些底層實現方式上也均有不同,在此不多做介紹,感興趣可另尋資料,在此需記住,此處使用隨機流的作用為第二步做准備,且唯一,其中參數1為File對象,構造方法重載的參數1可為文件路徑,參數2的取值可有4種,如下(取至JAVA官方文檔):
  1. "r"僅供閱讀。調用結果對象的任何寫方法都會引發IOException。(Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown. )

  2. "rw"開放閱讀和寫作。如果該文件不存在,那么將嘗試創建它。(Open for reading and writing. If the file does not already exist then an attempt will be made to create it. )

  3. “rws”和“rw”一樣,對文件內容或元數據的每次更新都要同步寫入底層存儲設備。(Open for reading and writing, as with "rw", and also require that every update to the file's content or metadata be written synchronously to the underlying storage device. )

  4. “rwd”和“rw”一樣,都是打開的,可以讀寫,並且還要求對文件內容的每次更新都要同步寫入底層存儲設備。(Open for reading and writing, as with "rw", and also require that every update to the file's content be written synchronously to the underlying storage device. )

  • 上述代碼中標注2位置中,通過隨機流獲取到一個讀寫兼並的通道,實際上獲取IO通道的方式並不僅僅只有此種方式,但是在此處需要注意的是,順序讀寫所需的通道需兼並讀寫(第一步中參數2取值需為:rw,rws,rwd),如果不是,則會觸發IO異常,除此之外,上述提到過使用其他方式也可以獲取到文件IO通道,比如:
FileInputStream fileInputStream = new FileInputStream(file);
FileChannel fileChannel = fileInputStream.getChannel();

運行結果,標記3處拋出異常:NonWritableChannelException
或者:

FileOutputStream fileInputStream = new FileOutputStream(file);
FileChannel fileChannel = fileInputStream.getChannel();

運行結果,標記3處拋出異常:NonReadableChannelException
從上可以看到,不管是FileInputStream還是FileOutputStream獲取到的IO通道,均有局限性,不適用MappedByteBuffer。

  • 上述代碼中標記3位置中,通過IO通道將該文件的內容(或某個區域)直接映射到內存中,並且對該內存做的修改直接會傳播到文件(除了PRIVATE模式,后續介紹),通過FileChannel對象的map();api進行映射,參數一指定映射方式,有如下三種(取至JAVA官方文檔):
  1. 只讀:任何修改結果緩沖區的嘗試都將導致拋出ReadOnlyBufferException。(MapMode.READ_ONLY) (Read-only: Any attempt to modify the resulting buffer will cause a ReadOnlyBufferException to be thrown. (MapMode.READ_ONLY) )

  2. 讀/寫:對產生的緩沖區所做的更改最終將傳播到文件;它們可能對映射了相同文件的其他程序可見,也可能不可見。(MapMode.READ_WRITE) (Read/write: Changes made to the resulting buffer will eventually be propagated to the file; they may or may not be made visible to other programs that have mapped the same file. (MapMode.READ_WRITE) )

  3. Private:對產生的緩沖區所做的更改不會傳播到該文件中,並且不會對映射了該文件的其他程序可見;相反,它們將導致創建緩沖區修改部分的私有副本。(MapMode.PRIVATE) (Private: Changes made to the resulting buffer will not be propagated to the file and will not be visible to other programs that have mapped the same file; instead, they will cause private copies of the modified portions of the buffer to be created. (MapMode.PRIVATE) )

參數二代表從指定位置開始映射,0表示從頭開始映射全部內容,參數三表示要映射的區域大小,可超出文件大小(如字符長度為3,此處可填寫6或者其他),但不可為負數或超出Integer.MAX_VALUE.
實際上到此處,IO通道已經完成了它的任務,可關閉。(在標記3之后任意位置可執行fileChannel.close()而不影響運行結果)
此處簡要說明了個參數的意思,要加深了解建議自己建立Demo並更改此處參數觀察運行結果。

  • 上述代碼中標記4位置中,通過MappedByteBuffer對象的position(); API設置寫入位置,官方解釋如下:
    Sets this buffer's limit. If the position is larger than the new limit then it is set to the new limit. If the mark is defined and larger than the new limit then it is discarded.

  • 上述代碼中標記5位置中,將內容傳輸到緩沖區,可理解為寫入,因為緩沖區的變動會傳播到實際文件中,除了PRIVATE。

  • 上述代碼中標記6位置中,返回下一次操作時的位置。

此篇文章簡要說明了一下JAVA順序IO,有些地方沒有詳細說明,會持續維護更新此篇文章,感謝大家。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM