2013-08-24 105 views
1

我剛剛在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個字節這樣的差別?你也可以建議我可以對代碼做任何改進。

非常感謝,我感謝幫助:)。

回答

1

您正在嘗試編寫使用ASCII一個新行(不是空格) - 見this table

但是,您選擇的UTF編碼可能不是8位,而只寫8位,所以2個或更多8位的組合會創建一些奇怪的符號。

0寫道根本無效,而不是一個新行或空白。

試試這個:

raf.writeChar(' '); 
0

爲「約翰」字節寫入到在這兩種情況下(raf.writeByte(10);raf.writeByte(0);)文件。但是,您的文本編輯器選擇以不同的方式解釋文件。使用十六進制編輯器來查看真的是正在寫入。