Using Files in Java

To really use streams, you need to use files. So this chapter will cover files first. Java supports two kinds of files:

  • File—Can only be written to sequentially

  • RandomAccessFile—Can be read from or written to at any point in the file

To be able to use a file in Java, you create a File or RandomAccessFile object.

Warning

It is critical to remember that creating a File object such as

File myFile = new File("/export", config.dat");

does not have anything to do with whether or not this file exists. You can execute this constructor for a nonexistent file. Java does not throw an exception for a nonexistent file until you actually try to create a stream that uses the file.

File: Code Example

The File class has three constructors ...

Get PURE Java™ 2 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.