Next: The FileOutputStream class. Up: Files. Previous: None.
Textbook: Section 14.2
Java has a large library of classes in the java.io package related to working with files. It's quite extensive and confusing. Today we're going to investigate three of the basic classes: File, FileOutputStream, and FileInputStream.
A File object represents the name of a file on the disk. It allows you to work with the file as an entire object - not looking inside the file, but asking questions about the file's attributes or doing something that works with the file as a whole.
The most basic constructor for a File takes a string as parameter giving the complete location of where the file is located.
This creates a File variable source, representing the file name ``CopyFile.java''. The parameter names the file just as you would name regular files. In Unix, a path name beginning with slash (`/') is relative to the root directory, and otherwise it is relative to the current directory (from which you invoked the program). You can name directories to move down the file hierarchy (or use the ``..'' directory to move up the hierarchy).File source = new File("CopyFile.java");
File source2 = new File("CS160/Lab9/CopyFile.java"); File source3 = new File("/usr/people/classes/Java/csbsju");
The File object represents a file's name, not the file itself. Thus, you can create a File object to represent a name, even if a file of that name doesn't exist.
The first set of methods that you can perform on a File object relate to answering questions about the file.
For example:
if(!source.exists()) { IO.println("The file ``" + source.getName() + "'' doesn't exist."); System.exit(-1); } else if(!source.canRead()) { IO.println("The file ``" + source.getName() + "'' exists, " + "but it isn't accessible."); System.exit(-1); }
There are also some for manipulating the file whole.
Next: The FileOutputStream class. Up: Files. Previous: None.