Javaで固定長のランダムアクセスファイルを作成する方法を示すYouTubeのチュートリアルを見ました。クラスwriteBytes
内のメソッドの概念と少し混乱しています。RandomAccessFile
// 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);
NEW ファイルに次の内容を保存します。
ここでは正しく見えないかもしれませんが、John の後に空白があり、名前は実際に読めます。
0 バイトと 10 バイトの使用にこのような違いがある理由を説明していただけますか?? また、コードに加えることができる改善を提案してください。
どうもありがとう、私は助けに感謝します:)。