我刚刚在 youtube 上观看了一个教程,展示了如何在 java 中创建固定长度的随机访问文件。我对 RandomAccessFile
类中的 writeBytes
方法的概念有些困惑。
// 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);
在新文件中存储以下内容:John
您可能无法在此处正确看到它,但在 John 之后有一个空格并且该名称实际上是可读的。
你们能解释一下为什么使用 0 字节和 10 字节会有这么大的区别吗??另外,您能否建议我可以对代码进行的任何改进。
非常感谢,感谢您的帮助:)。
最佳答案
您正在尝试使用 ASCII 写一个新行(不是空格)- 参见 this table .
但是,您选择的 UTF 编码可能不是 8 位,而您只写了 8 位,因此 2 个或更多 8 位的组合会产生一些奇怪的符号。
0 只写空,而不是新行或空格。
试试这个:
raf.writeChar(' ');
关于Java 固定长度随机存取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18422677/