Java Reference
In-Depth Information
through the file extension
.xml
. You'll learn more about XML and how to write and read XML files in the
last two chapters of the topic.
You can access an existing file to read it or write it in two different ways, described as
sequential access
or
random access
. The latter is sometimes referred to as
direct access
. Sequential access to a file is quite
straightforward and works pretty much as you would expect. Sequential read access involves reading bytes
from the file starting from the beginning with byte 0. Of course, if you are interested only in the file con-
tents starting at byte 100, you can just read and ignore the first 100 bytes. Sequential write access involves
writing bytes to the file starting at the beginning if you are replacing the existing data or writing a new file,
and writing bytes starting at the end if you are appending new data to an existing file.
The term random access is sometimes misunderstood initially. Just like sequential access, random access
is just a way of accessing data in a file and has nothing to do with how the data in the file is structured or how
the physical file was originally written. You can access any file randomly for reading and/or writing. When
you access a file randomly, you can read one or more bytes from the file starting at any point. For example,
you could read 20 bytes starting at the 13th byte in the file (which is the byte at offset 12, of course) and
then read 50 bytes starting at the 101st byte or any other point that you choose. Similarly, you can update an
existing file in random access mode by writing data starting at any point in the file. In random access mode,
the choice of where to start reading or writing and how many bytes you read or write is entirely up to you.
You just need to know the offset for the byte where a read or write operation should start. Of course, for
these to be sensible and successful operations, you have to have a clear idea of how the data in the file is
structured.
WARNING
First a note of caution: Before running any of the examples in this chapter, be
sure to set up a separate directory for storing the files that you are using when you are testing
programs. It's also not a bad idea to back up any files and directories on your system that you
don't want to risk losing. But of course, you do back up your files regularly anyway — right?
WARNING
The old adage “If anything can go wrong, it will,” applies particularly in this
context, asdoesthecomplementary principle “Ifanythingcan'tgowrong,itwill.”Remember
also that the probability of something going wrong increases in proportion to the inconveni-
ence it is likely to cause.
FILE OUTPUT
The
Files
class provides three ways for you to access a file to write it:
• The
newOutputStream()
method opens or creates a file specified by a
Path
object. The method
returns a reference to an unbuffered
OutputStream
object encapsulating the file. If you wrap this