









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to working with binary files in java, including how to write and read raw data using the file and randomaccessfile classes. Topics covered include creating and deleting files, checking permissions, writing and reading integers, doubles, characters, strings, and classes, and handling exceptions when reading. Random file access is also discussed.
Typology: Slides
1 / 17
This page cannot be seen from the preview
Don't miss anything!










Homework 5 due on Monday
The File class allows you to do basic operations with files, such as:
So far we have been dealing with “text” files which store characters Sometimes it is more convenient to use “binary” files, which store raw data Unfortunately, binary files are hard to read if you don't know their format
When writing to text files, we used println() However, to write to data files you need to run a specific method for each type of thing: writeInt(), writeDouble(), writeChar(), ... writeUTF() is for writing Strings writeObject is for writing classes/arrays (See: WriteBinaryFile.java) Docsity.com
In order to write classes to binary files, you need to add something to your class definition: All you need to put is “implements Serializable” and you can write your class to a file (if you have an instance of another class in yours, that class also needs to be Serializable) (We will learn about “implements”in Ch 13)
Unfortunately, there is no way to tell if you are at the end of a binary file Instead you need to catch EOFException (when there is no more data) You can get other exceptions if you try to read the incorrect type of data (See: ReadBinaryFileBad.java) Docsity.com
Text files:
So far, we have been...
Random access is done by storing a file pointer (much like an array index, starting at 0) The file pointer starts at the beginning of the file (be careful not to write over old data) New methods with random access: seek() - moves to that spot in the file length() - length of the file getFilePointer() - where you are in the fileDocsity.com
Unfortunately, RandomAccessFile class does not have readObject() and writeObject() The file pointer is annoying because it is the actual bytes, instead of index For example: an int is four bytes, so if you write 2 ints, the first one starts at spot 0 and the second one at spot 4 (See: RandomAccess.java)