CSC1110 Exercise 12
File Input/Output
Reading and writing files is one of the most common actions in modern programming. All data is stored in a file somewhere, so to use data in any capacity, we need to be able to store it in files and read it from files into memory. There are many ways to read and write files in Java, but we will focus on three in this exercise:
- Pure text
- Binary data
- Binary objects
Text File I/O
There are numerous ways to read and write text files in Java. The simplest way to read text from an existing text file is to use a Scanner
object. A Scanner
is quite flexible in that it can read text from a variety of sources, as long as that source gives the Scanner
a String
. Some examples of sources for a Scanner
are
System.in
- Keyboard inputString
objects - Will be read as if theString
were typed in- Paths/Files - Will attempt to read the file referenced by the
Path
orFile
object
Note that to have a Scanner
read from a file, you would need to pass in a File
or Path
object, not just the filename. This is because the filename is a String
and would be read by the Scanner
as a String
.
To write to a text file, the simplest way is to use a PrintWriter
object. The PrintWriter
uses the same methods that System.out
uses, such as println()
, print()
, printf()
, etc.
Binary File I/O
To store non-text data, we can use binary files to efficiently store primitive data types. This is done using the DataInputStream
and DataOutoutStream
objects. Both of these require a FileInputStream
or FileOutputStream
parameter to interface with the File
itself. These streams only need a filename to access the data.
Object File I/O
In Java, there are times when it is necessary to save instances of an objects. Rather than save each individual instance variable, then reload them into new objects, we can store entire objects into a file using the ObjectOutputStream
and ObjectInputStream
objects. Like the binary files above, a FileInputStream
or FileOutputStream
is required for these objects.
Exercise
You have been given some values that you will need to store in all three of these types of files. There is a provided Dyad
record to store integer values for writing an object. You should write the data to three separate files, handling any checked exceptions that arise with useful messages. Once you have written the files, you will then create variables (two for each file) and read in your three files. Print out your variables to verify that your data was successfully written and read,
Submission Instructions
Commit and push your code to your repository.