Aqua Phoenix
     >>  Lectures >>  Java 6  
 

Navigator
   
 
       
   

6.1 File Input/Output

File I/O in Java is not unlike I/O programming in other programming languages. We distinguish Text files from Binary files, and apply different methods of handling both.

There are a few notable differences still. Because of the object-oriented design, file reading and writing is divided into several logistical steps:

  • Files are encapsulated as objects, and are no longer solely pathnames.
  • The act of reading or writing a file is encapsulated in a separate object.
  • Parsing the input or output in some special manner (text versus binary) is encapsulated by a third object.
  • Parsing contents from the file after that contents is read is performed in another step.

A lot of classes related to input/output are found in the package java.io. It is thus necessary to import this package in the beginning of a Java source file:

import java.io.*;

6.2 File

The object File is an encapsulation for and representation of a file or a directory. File objects do not only represent existing files and directories, but also non-existing ones. The File object contains various methods for testing the type of a file, manipulating the file (deletion, creation, etc.), and reading a directory's contents (list of files).

File objects are very common in Java, and as opposed to passing around String values to denote file names, File objects are used more frequently. Once a File object for a file is created, it is very easy to manipulate and obtain information from. A side effect of the frequent usage of the File object, is that many methods inside the File class are duplicates with different names but having the same functionality. The only difference is the returned value - either a File object or a String. Keep this in mind when working with files - method names can be somewhat misleading at times.

A File object is created using the relative or absolute path:

File someFile = new File("/usr/local/home/ahaubold/someFile.txt");
File someFile = new File("c:\\documents and settings\\ahaubold\\someFile.txt");
File someFile = new File("someFile.txt");
or the directory and file name can be separately specified:

File someFile = new File("/usr/local/home/ahaubold", "someFile.txt");
Besides keeping track of a file's name and parent directories, the File object also maintains file system specific information, e.g. the file separator, whether a backslash (DOS and Windows), or a forward slash (all other OS's). The file separator is a constant string that can be references as File.separator.

There are a number of methods to retrieve different representations for the file denoted by the file's File object:

  • Absolute path: someFile.getAbsolutePath() returns the absolute path of the file
  • Canonical path: someFile.getCanonicalPath() returns the absolute shortest path of the file
  • Name: someFile.getName() returns the name of the file, i.e. the filename without any directories
  • Parent: someFile.getParent() returns the parent, i.e. the name of the file/directory immediately above this file
  • Path: someFile.getPath() returns the path of the file as denoted by the constructor

These methods can be confusing and they tend to overlap in meaning. Here are a few examples to explain the differences:

Given an absolute file location:

File someFile = new File("/usr/local/home/someFile.txt");
absolute path: /usr/local/home/someFile.txt canonical path: /usr/local/home/someFile.txt name: someFile.txt parent: /usr/local/home path: /usr/local/home/someFile.txt Given a relative file location:

File someFile = new File("someFile.txt");
absolute path: /usr/local/home/ahaubold/someFile.txt canonical path: /usr/local/home/ahaubold/someFile.txt name: someFile.txt parent: null path: someFile.txt Given a relative file location, including a reference to the parent:

File someFile = new File("../someFile.txt");
absolute path: /usr/local/home/ahaubold/../someFile.txt canonical path: /usr/local/home/someFile.txt name: someFile.txt parent: .. path: ../someFile.txt Rules:
  • getParent() returns the parent of the file as given by the constructor. If not specified in the constructor, getParent() returns null. To retrieve the parent of a file regardless of constructor, first use getCanonicalPath(), then use getParent().
  • getName() always returns the name of the file or directory.
  • getAbsolutePath() returns the absolute path of the file, including any additional references passed to the constructor.
  • getCanonicalPath() returns the true absolute path.
  • getPath() returns the relative path

Once a File object has been created, various methods can be used to manipulate the file. The most common ones are:

  • canRead(), e.g. someFile.canRead(), (true/false)
  • canWrite() (true/false)
  • delete()
  • exists() (true/false)
  • isFile() (true/false)
  • isDirectory() (true/false)
  • list() returns a String array of files that are contained in the File object's directory, if the file object is a directory
  • listFiles() returns a File array of files in the File object's directory
  • mkdir() creates a directory denoted by the File object
  • mkdirs() creates the directory and any non-existing parent directories

Note: Java, while developed by the company that is based on Unix, does not handle Unix-specific file details, e.g. permissions. It is not possible to set or get Read, Write, and Execute permission parameters for Owner, Group, and Other.

6.2.1 Examples

List all files in the current directory, and tag each line with a letter to denote File (F), or Directory (D), and readable (R), and writable (W):

File root = new File("."); // current directory
File[] files = root.listFiles();
for (int i = 0; i < files.length; i++) {
  if (files[i].isFile()) {
    System.out.print("F ");
  } else if (files[i].isDirectory()) {
    System.out.print("D ");
  } else {
    System.out.print("? ");
  }
  if (files[i].canRead()) {
    System.out.print("R ");
  } else {
    System.out.print("  ");
  }
  if (files[i].canWrite()) {
    System.out.print("W ");
  } else {
    System.out.print("  ");
  }
  System.out.println(files[i].getName());
}
Sample output:

...
F R W errlog
F R W .java.policy.disable
F R W .fonts.cache-1
D R W cmspDB
D R W matlab
F R W Columbia CS Admin.mbx
F R W cslp-header.xcf
D R W cslp
F R W ibm_in.txt
F R W ibm_out.txt
F R W t.java
F    someFile.txt
F R W t.class
D R W gateway