我剛剛在YouTube的教程展示瞭如何在Java中創建固定長度隨機訪問文件。我對RandomAccessFile
類中的writeBytes
方法的概念稍有困惑。Java的定長隨機訪問文件
// Create an instance of the RandomAccessFile class
RandomAccessFile raf = new RandomAccessFile("RAF1.dat", "rw");
// Get the length of the file so new entries
// Are added at the end of the file
raf.seek(raf.length());
// Max input length of the persons name
int recordLength = 20;
// Each record will have a byte length of 22
// Because writeUTF takes up 2 bytes
int byteLength = 22;
// Just a random name to stick in the file
String name = "John";
// Write the UTF name into the file
raf.writeUTF(name);
// Loop through the required whitespace to
// Fill the contents of the record with a byte
// e.g recordLength - nameLength (20 - 4) = 16 whitespace
for (int i = 0; i < recordLength - name.length(); i++) {
raf.writeByte(10);
}
上面是我用來寫入隨機存取文件的代碼。正如你所看到的我正在使用raf.writeByte(10);以填補記錄中的空白。
raf.writeByte(10);
存儲在文件中的以下內容:Ѐ潊湨ਊਊਊਊਊਊਊਊ
但是當我改變raf.writeByte(10);
到raf.writeByte(0);
,並創建一個新的文件...
raf.writeByte(0);
商店在新文件中的以下內容:約翰
你可能無法看到它正確的,但這裏有空白約翰後的名稱實際上是可讀的。
難道你們,請解釋一下爲什麼會出現在使用0字節和10個字節這樣的差別?你也可以建議我可以對代碼做任何改進。
非常感謝,我感謝幫助:)。