EOFException Class
Definition
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Signals that an end of file or end of stream has been reached unexpectedly during input.
Remarks
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
Constructs an EOFException with null as its error detail message.
A constructor used when creating managed representations of JNI objects; called by the runtime.
Constructs an EOFException with null as its error detail message.
Fields
Properties
Returns the cause of this throwable or null if the cause is nonexistent or unknown.
(Inherited from Throwable)
The handle to the underlying Android instance.
(Inherited from Throwable)
Creates a localized description of this throwable.
Returns the detail message string of this throwable.
(Inherited from Throwable)
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
Methods
Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.
(Inherited from Throwable)
Fills in the execution stack trace.
Initializes the cause of this throwable to the specified value.
Prints this throwable and its backtrace to the standard error stream.
Prints this throwable and its backtrace to the standard error stream.
Prints this throwable and its backtrace to the standard error stream.
Sets the Handle property.
Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.
(Inherited from Throwable)
Explicit Interface Implementations
| IJavaPeerable.Disposed() | (Inherited from Throwable) |
| IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Throwable) |
| IJavaPeerable.Finalized() | (Inherited from Throwable) |
| IJavaPeerable.JniManagedPeerState | (Inherited from Throwable) |
| IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Throwable) |
| IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Throwable) |
| IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Throwable) |
Extension Methods
Performs an Android runtime-checked type conversion.
Java Exception Handling – EOFException
Making our way through our detailed Java Exception Handling series, today we’ll tackle the EOFException. Most developers will probably recognize that the acronym EOF in this exception name usually stands for “end of file”, which is exactly the case here. When an EOFException is thrown in Java, this indicates that the end of the file or stream has been reached unexpectedly.
The Technical Rundown
All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:
Full Code Sample
Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.
When Should You Use It?
Since the appearance of an EOFException simply indicates that the end of the file or memory stream was reached, the best way to show how to properly use and handle this exception is in code, so let’s jump right into our sample.
We start with a basic Book class that contains a few fields, which we’ll be using to create some real-world objects to output to a local file.
Next we have the WriteBooksToFile() method, which does just as the name suggests:
By using a DataOutputStream instance we’re able to loop through the collection of Books found in our DATA property and create a new string via the writeUTF(. ) method. Once complete, we close the stream, and all is taken care of. Executing this method produces the following output to the log:
To confirm the formatted Book strings are being locally saved we can open up the local books.txt file. Here’s the current contents of that file (Note that this file is actually in binary, even though it mostly appears as plain text):
Cool. Now, to retrieve the data that was saved to books.txt we start with the ReadBooksFromFileImproperly() method:
Executing this method produces the following output:
Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices. Try Airbrake free for 30 days!
Monitor Your App Free for 30 Days
Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.
java io eofexception как исправить
Этот код бросает java.io.EOFException, и я не уверен, почему это происходит.
Содержимое входного файла:
Результат совершенно неожиданно, и я предполагаю, что исключение выбрасывается, потому что по какой-то причине значение суммы велико, чем максимальное значение int.
Я попытался изменить «int sum = 0» на «long sum = 0» и получил те же результаты.
Я прокомментировал следующее:
После этого я получил следующее исключение:
Если это помогает, я использую Ubuntu 18.04 LTS.
java version «1.8.0_181» Java (TM) SE Runtime Environment (сборка 1.8.0_181-b13) 64-разрядная серверная виртуальная машина Java HotSpot TM (сборка 25.181-b13, смешанный режим)
Я начинающий Java-программист, следуя java tutorials.
Он компилируется отлично, но вывод:
Обратите внимание, что DataStreams обнаруживает условие конца файла, перехватывая EOFException вместо проверки на недопустимое возвращаемое значение. Все реализации методов DataInput используют EOFException вместо возвращаемых значений.
Итак, означает ли это, что catching EOFException является нормальным, поэтому просто поймать его и не обрабатывать, это хорошо, что означает, что конец файла достигнут?
Если это означает, что я должен это обработать, пожалуйста, сообщите мне, как это сделать.
ИЗМЕНИТЬ
Или я не мог ничего сделать, чтобы обрабатывать исключение, потому что это нормально.
Я хочу прочитать файл и если там email существует — ничего не делать, а если не существует — записать email в файл.
2 ответа 2
Попробуйте добавить проверку в while
Всё ещё ищете ответ? Посмотрите другие вопросы с метками java файлы или задайте свой вопрос.
Похожие
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2019 Stack Exchange Inc; пользовательское содержимое попадает под действие лицензии cc by-sa 4.0 с указанием ссылки на источник. rev 2019.11.15.35459






