exception - Is Java's EOFException exceptional? -
It seems dirty to use an exception that has reached the end of a file. Every file we read is finished, so it does not seem extraordinary or unpredictable. Apart from this, I do not like to use an exception for the non-efferent flow of my program.
I'm talking about signaling the end of a data input stream:
Imagine the file that is compiled with the following messages ...
< Code> ----------------- ------------ ------- 2-byte LENGTH - - N-byte payments -, Where N = LENGTH; ----------------- ------------------
... and Reading this file with DataInputStream:
In DataInputStream = New DataInputStream (...); ... try {while (true) {short length = in.readShort (); Byte [] B = new byte [length]; In.readFully (b); }} Hold (EOFException e) {} ...
In this example, an EOFException is thrown out by calling in.readShort ()
. Should I understand the number of bytes in the file, and in fact it should be read by the number of bytes (by total - = length
by zero), and exit the while-loop without exception? I am looking for the best practice.
Should I do something like this?
long total = file.length (); While (total> gt;) {short length = in.readShort (); Total - = Length; Byte [] B = new byte [length]; In.readFully (b); }
The API specification specifies that EOFException indicates the end of the file or the end of the stream during the input unexpectedly but its use at the end of the stream Data is also used to indicate the input streams.
What should I do when expecting to be exceptional?
DataInput.readFully
look for the method:
This method is blocked until one of the following methods: * b is the length of byte of input data available, in this case a normal return is made. * End of file has been detected, in this case an EOFException is thrown. * An I / O error occurs, in this case an IOException is thrown in addition to EOFException. So
is the idea that it is going to read the b.length byte of data, or if you can not do this, then I / O error or at the end of the file B .length bytes can be read before.
So you should know that how many bytes you want to read before calling DataInput.readFully
. If you go before the end of the file, it is considered unusual behavior, and therefore, you get an exception.
Comments
Post a Comment