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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.