Professional Documents
Culture Documents
• After you have read and studied this supplement, you should be
able to
use File objects in your program to access the files on your
computer system;
use a FileDialog object to easily select a particular file;
write exception-handling code using try-catch blocks.
• In this supplement you will learn more about file input and file
output i.e. about how to read data from a file and how to save
data to a file.
• We use the term “file access” to refer to both read and write
operations. If we need to be precise, we will write “read access”
or “write access”.
• Operating systems such as Windows, Linux and MacOS have
different methods of describing file systems and this presents a
problem for Java which is intended to be platform independent.
• Java overcomes this problem by providing a class File (in
java.io) that gives an abstract, system-independent view.
java dbases
exercises examples
book-exercise
Programming 2 © 2022-23 Slide SM5.5
D E Newton
Java Supplementary Material 5: More on file input and output
Two forms of the constructor
• And
"../chapter04"
is equivalent to the absolute pathname
"F:/java/examples/chapter04"
where the two dots (..) in the first string mean "the directory
above" i.e. the parent directory.
• After the dialog box closes, the name of the file selected,
readme.txt, is retrieved using the getFile() method. The
statement
String filename = fileBox.getFile();
assigns the name of the file selected to filename.
• Alternatively, if the Cancel button of the FileDialog is
clicked, then the getFile() method returns null.
• We can also get the pathname to the directory from which the
user selected the file. Continuing with the same example,
executing
String directoryPath = fileBox.getDirectory();
will assign the pathname
F:\java\examples\chapter02
to directoryPath.
Programming 2 © 2022-23 Slide SM5.14
D E Newton
Java Supplementary Material 5: More on file input and output
FileDialog in SAVE mode
see lines 39-52 for the first try block followed by lines
55-59 which will be executed if a EOFException occurs;
lines 63-66 which will be executed if a FNFException
occurs;
lines 70-73 which will be executed if an IOException
occurs.
Note an alternative, older way of linking the data files
with the File object on lines 43-44. Do NOT use this
way.
Programming 2 © 2022-23 Slide SM5.20
D E Newton
Java Supplementary Material 5: More on file input and output
Exception handling code example cont./