Return to Tutorial Index

Back to the home page of this site


Java2 Certification


You can discuss this topic with others at
Read reviews and buy a Java Certification book at

The Rusty Harold/O'Reilly Java I/O book

O'Reilly have published a book specifically about Java I/O It get very good reviews at amazon. If you buy it from the following links I will get a small commission on the purchase

Buy from or from

11) The package

Objective 1)

Write code that uses objects of the file class to navigate a file system.

In his excellent book Just Java and Beyond Peter van der Linden starts his chapter on File I/O by saying

"It is not completely fair to remark, as some have, that support for I/O in java is "bone headed".

I think he was implying that it is not the perfect system, and so it is an area worthy of double checking your knowledge of before you go for the exam. When you are learning it you have the compensation that at least it is a useful area of the language to understand.

The package is concerned with input and output. Any non trivial program will require I/O. Anything from reading a plain comma delimeted text file, a XML data file or something more exotic such as a network stream. The good news is that the Programmer Certification Exam only expects you to understand the basics of I/O, you do not have to know about Networking or the more exotic aspects of I/O.

Java I/O is based on the concept of streams. The computer term streams was first popularised with the Unix operating system and you may like to consider it as being an analogy with a stream of water. You have a stream of bits coming in at one end, you apply certain filter to process the stream. Out the other end of the pipe you send a modified version of the stream which your program can process..

The names of the I/O Stream classes are not intuitive and things do not always work as you might guess.

The File Class

The File class is not entirely descriptive as an instance of the File class represents a file or directory name rather than a file itself.

My first assumption when asked about navigating a file system would be to look for a method to change directory. Unfortunately the File class does not have such a method and it seems that you simply have to create a new File object with a different directory for the constructor.

Also the exam may ask you questions about the ability to make and delete files and directories which may be considered to come under the heading of navigating the file system.

Creating an instance of the File class does not create a file in the underlying operating system

The file class offers


To delete a file or directory

mkdir() and mkdirs()

To create directories.

The File class contains the list() which returns a string array containing all of the files in a directory. This is very handy for checking to see if a file is available before attempting to open it. An example of using list.

public class FileNav{
public static void main(String argv[]){
          String[] filenames;
          File f = new File(".");
          filenames = f.list();
          for(int i=0; i< filenames.length; i++)

This simply outputs a list of the files in the current directory ("*.*")

Platform Independence

The file class is important in writing pure java. I used to think that pure Java was just about not including native code, but it also refers to writing platform independent code. Because of the differences between in the way File systems work it is important to be aware of platform dependencies such as the directory separator character. On Win/DOS it is a backslash \, on Unix it is a forward slash / and on a Mac it is something else. You can get around this dependency by using the File.separator constant instead of hard coding in the separator literal. You can see this in use in the Filer example program that follows.

A program to navigate the file system

The following code is rather long (90 odd lines), but if you can make sense of this you will know most of what you need to understand the objective. The program allows you to browse the files in a directory and to change directories. It was partly inspired by some code in the Java in a Nutshell Examples book from O'reilly. A book I highly recommend. Here is a screen shot of this program in action under Linux

import java.awt.*;
import java.awt.event.*;
public class Filer extends Frame implements ActionListener{
  Marcus Green October 2000 Part of the Java Programmer Certification
  tutorial available at Addressing the objective to be able
  to use the File class to navigate the File system.This program will show a 
  list of files in a directory .Clicking on a directory will change to the directory
  and show the contentsNote the use of File.separator to allow this to work on
  Unix or PC (and maybe even the Mac)
  List lstFiles;
  File currentDir;
  String[] safiles;
  int iEntryType = 6;
  int iRootElement = 0;
  int iElementCount = 20;
  public static void main(String argv[]){
    Filer f = new Filer();
    setLayout(new FlowLayout());
    lstFiles = new List(iElementCount);
    //set the current directory
    File dir = new File(System.getProperty("user.dir"));
    currentDir = dir;
    new WindowAdapter(){
      public void windowClosing(WindowEvent e){

    } );


  public  void actionPerformed(ActionEvent e){
    int i = lstFiles.getSelectedIndex();
    String sCurFile = lstFiles.getItem(i);
    //Find the length of the file name and then
    //chop of the filetype part (dir or file)
    int iNameLen = sCurFile.length();
    sCurFile = sCurFile.substring(iEntryType,iNameLen);
    File fCurFile = new File(currentDir.toString()+File.separator + sCurFile);
  public void  upDir(File currentDir){
    File fullPath = new File(currentDir.getAbsolutePath());
    String sparent = fullPath.getAbsoluteFile().getParent();
   if(sparent == null) {
    //At the root so put in the dir separator to indicate this
      lstFiles.add(" "+File.separator+" ",iRootElement);
      File fparent = new File(sparent);
  public void listDirectory(File dir){      
    String sCurPath = dir.getAbsolutePath()+File.separator ;
    //Get the directorie entries
    safiles = dir.list();
    //remove the previous lis and add in the entry
    //for moving up a directory
    lstFiles.addItem("[ .. ]");
    String sFileName = new String();
    //loop through the file names and 
    //add them to the list control
    for(int i=0; i< safiles.length; i++){
      File curFile = new File(sCurPath + safiles[i]);
          sFileName = "[dir ]" + safiles[i];
            sFileName = "[file]"+safiles[i]; 


Question 1)

Which of the following will distinguish between a directory and a file

1) FileType()
2) isDir()
3) isDirectory()
4) getDirectory()

Question 2)

Which of the following methods of the File class will delete a directory or file

1) The file class does not allow you to delete a file or directory
2) remove()
3) delete()
4) del()

Question 3)

How can you obtain the names of the files contained in an instance of the File class called dir?

1) dir.list()
2) dir.list
3) dir.files()
4) dir.FileNames()

Question 4)

Which of the following will populate an instance of the File class with the contents of the current directory?

1) File f = new File();
2) File f = new File("*.*");
3) File f = new File('*.*');
4) File f = new File(".");

Question 5)

Given the following code

File f = new File("myfile.txt");

What method will cause the file "myfile.txt" to be created in the underlying operating system.?

1) f.write();
2) f.close();
3) f.flush();
4) none of the above

Question 6)

Which of the following will chenge to the next directory above the current directory
1) chDir("..");
2) cd(".");
3) up();
4) none of the above

Question 7)

Which of the following are fields or methods of the File class
1) getParent()
2) separator
3) dirname
4) getName();


Answer to Question 1)

3) isDirectory()

Answer to Question 2)

3) delete()

Answer to Question 3)

1) dir.list()

The list method will return a string array containing the contents of the current directory.

Answer to Question 4)

4) File f = new File(".");

This construction for the File class will obtain the contents of the current directory on a Dos or Unix style system but I am not sure what might happen on some other system with a more exotic file structure such as the Mac OS.

Answer to Question 5)

4) none of the above

The File class mainly just describes a file that might exist. To actually create it in the underlying operating system you need to pass the instance of the File class to an instance of one of the OutputStream classes.

Answer to Question 6)

4) none of these
Java has no direct way to change the current directory. A way around this is to create a new instance of the file class pointing to the new directory

Answer to Question 7)

1) getParent()
2) separator
4) getName();

Other Sources on this topic

You can browse the samples of the O'Reilly Java I/O book at

This topic is covered in the Sun Tutorial at

The Java API on the File class at Sun

The JLS on Java IO a bit academic and bare

Richard Baldwin on I/O

Joyothi has some handy tables for the I/O classes at

Last updated
24 Oct 2000
copyright © Marcus Green 2000
most recent version at