我正在使用FileInputStream
以文件的字節數讀取。代碼(在其正確的形式)如下:閱讀完所有的文件,並把每一組的4 bytes
成float
時當使用String.valueOf或Float.toString時,爲什麼這個循環變得無限?
String s = "";
try {
File file = new File(...);
FileInputStream file_input = new FileInputStream(file);
DataInputStream data_in = new DataInputStream(file_input);
while (true) {
try {
for (int index = 0; index < 4; index++) {
byteArray[index] = data_in.readByte();
}
} catch (EOFException eof) {
break;
}
float f = readFloatLittleEndian(byteArray); // transforms 4 bytes into a float
//s += Float.toString(f); <- here's the problem
}
data_in.close();
} catch (IOException e) {
System.err.println(e.toString());
}
}
System.out.print(s);
如果我爲這段代碼運行,則循環結束。
但是,如果我取消註釋該行,該文件永遠不會結束,似乎一遍又一遍地遍歷文件。此外,打印f
(不使用Float.toString
或String.valueOf
)不會將其變成無限循環。
你有什麼證據表明它是一個無限循環(而不是慢)? –
我包含一個文件大小的計數器,並遞增計數器循環執行的次數。如果計數器大於此大小,我將它重置爲零,並輸出另一個計數器,顯示發生了多少次。當我這樣做,它打印1 2 3 4 ...並不停止。 – user473973
你是否嘗試用'catch(Exception e)'替換'catch(EOFException eof)',僅用於調試目的? (也許會引發另一個異常) – xav