[英]Reading specific bytes from RandomAccessFile and testing to see if they equal 0
第一次海报在这里。 预先感谢您查看我的问题。 我在做作业时遇到了很多麻烦,必须从RandomAccessFile中读取特定范围的字节,然后检查该字节范围,以查看它们是否都等于0。与此有关,但我发现没有什么很吸引人的。 提供的任何帮助将不胜感激。
该问题告诉我们,存在一个特定文件,其中包含学校中假设学生的数据。 这些学生中的每个人都用40字节的代码表示,但是文件的前四个字节必须是一个整数,该整数表示学校的学生总数(假设有75个)。 字节4到43代表第一个学生(#0),字节44到83代表第二个学生(#1),依此类推。 当学生转移到另一所学校时,他们的40个字节被全0(字符)覆盖。
我编写了一种名为“ transferStudent”的方法,该方法采用一个代表文件名的String和一个代表学生人数的整数。 如果有任何例外情况,或者文件由于某种原因未覆盖学生的数据,则返回false;否则,返回false。
到目前为止,这是我的工作:
public static Boolean transferStudent(String fileName, int studentNum) {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
file.writeInt(75);
try {
if (studentNum == 0) {
file.seek(4);
file.writeBytes("0000000000000000000000000000000000000000"); // 40 zero characters
file.seek(4);
for (int i = 0; i < 40; i++) {
if (file.read() == 0) {
return true;
}
}
return false;
}
else if (studentNum > 0) {
file.seek(4 + (studentNum * 40));
file.writeBytes("0000000000000000000000000000000000000000"); // 40 more zeroes
file.seek(4);
for (int i = (4 + (studentNum * 40)); i < (44 + (studentNum * 40)); i++) {
if (file.read() == 0) {
return true;
}
}
return false;
}
else {
return false;
}
}
catch (Exception e) {
return false;
}
}
每当我查看已创建的二进制文件时,在与studentNum对应的范围内确实存在0。 但是,控制台始终显示false-由于某些原因,检查无法正常进行。 我正要为此扯头发。 请帮忙!
您将ASCII零“ 0”与二进制零混淆了。 您正在编写前者,并为后者进行测试。 ASCII“ 0”占用两个字节。 请注意,“字符”和“字节”在Java中是不同的。
因此,我想我终于找到了问题所在:就像EJP所说的那样,我将ASCII零“ 0”与二进制零混淆了。 如前所述,ASCII零占用了两个字节的信息-这确实使我感到困惑:我查看了写入的文件,但似乎只有一个字节的信息用于写入每个“ 0”。 我将不得不对此主题进行更多研究。 除此之外,我的代码还有另一个问题-每次我运行该程序时,文件都会收到写入的零字符。 没问题,但是检查还有第二个问题-在使用循环进行检查时,我没有做任何事情来进一步推进文件指针。
因此,需要做两件事来修复我的代码:
首先,我必须找到一种方法来前进文件指针,以便正确读取我的RandomAccessFile中的每个位置。
其次,我必须在启动检查时检查适当的值:该值应该为“ 48”,这是字符“ 0”的ASCII值。
这是我的新代码:
public static boolean transferStudent(String fileName, int studentNum) throws IOException {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
boolean trueOrFalse = false;
file.writeInt(75);
try {
if (studentNum == 0) {
file.seek(4);
file.writeBytes("0000000000000000000000000000000000000000"); // 40 zero characters
file.seek(4);
for (int i = 0; i < 40; i++) {
file.seek(4 + i); // Here is where the file pointer is advanced in the for-loop - very crucial
if (file.read() == 48) { // Here is where the file is checked for the appropriate value - the ASCII value for "0"
trueOrFalse = true;
}
}
return trueOrFalse;
}
else if (studentNum > 0) {
file.seek(4 + (studentNum * 40));
file.writeBytes("0000000000000000000000000000000000000000"); // 40 more zeroes
file.seek(4 + (studentNum * 40));
for (int i = 0; i < 40; i++) { // The same happens here as above
file.seek((4 + (studentNum * 40)) + i); // ... and here also
if (file.read() == 48) {
trueOrFalse = true;
}
}
return trueOrFalse;
}
else {
return trueOrFalse;
}
}
catch (Exception e) {
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.