Java固定长度随机访问文件
我刚刚在youtube上观看了一个教程,展示了如何用java创建固定长度的随机访问文件。我对Java固定长度随机访问文件,java,file,storage,Java,File,Storage,我刚刚在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 // Ar
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);
}
//创建RandomAccessFile类的实例
RandomAccessFile raf=新的RandomAccessFile(“RAF1.dat”、“rw”);
//获取文件的长度,以便创建新条目
//添加到文件末尾
raf.seek(raf.length());
//人名的最大输入长度
int记录长度=20;
//每条记录的字节长度为22
//因为writeUTF占用2个字节
int bytellength=22;
//只是一个随机的名字粘贴在文件中
字符串name=“John”;
//将UTF名称写入文件
英国皇家空军司令部(姓名);
//循环使用所需的空白以
//用一个字节填充记录的内容
//例如recordLength-nameLength(20-4)=16个空格
for(int i=0;i
上面是我用来写入随机访问文件的代码。如你所见,我使用的是raf.writeByte(10);以填充记录中的空白
raf.writeByte(10)代码>在文件中存储以下内容:Ѐ潊湨ਊਊਊਊਊਊਊਊ
但是当我改变raf.writeByte(10)代码>到raf.writeByte(0)代码>并创建一个新文件
raf.writeByte(0)代码>将以下内容存储在新文件中:John
您可能无法在此处正确看到它,但John后面有空格,而且名称实际上是可读的
你们能解释一下为什么使用0字节和10字节有这么大的区别吗??另外,你能建议我对代码做些什么改进吗
非常感谢,非常感谢您的帮助:)。您正在尝试使用ASCII编写新行(不是空白)-请参阅
但是,您选择的UTF编码可能不是8位,而您只写8位,因此2个或更多8位的组合会产生一些奇怪的符号
0只写入null,而不是新行或空白
请尝试以下方法:
raf.writeChar(' ');
在这两种情况下,raf.writeByte(10);
或raf.writeByte(0);
)都会将“John”的字节写入您的文件。但是,您的文本编辑器选择以不同的方式解释文件。使用十六进制编辑器查看实际编写的内容