[英]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.