Return to Tutorial Index

Back to the home page of this site

morterboard

Java2 Certification
Tutorial

 

You can discuss this topic with others at http://www.jchq.net/discus
Read reviews and buy a Java Certification book at http://www.jchq.net/bookreviews/jcertbooks.htm


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 Amazon.com or from Amazon.co.uk


11) The java.io 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 java.io 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

delete()

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.

import java.io.*;
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++)
            System.out.println(filenames[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.*;
import java.io.*;
public class Filer extends Frame implements ActionListener{
  /**************************************************************
  Marcus Green October 2000 Part of the Java Programmer Certification
  tutorial available at http://www.jchq.net. 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();
    f.setSize(300,400);
    f.setVisible(true);
  }
  Filer(){
    setLayout(new FlowLayout());
    lstFiles = new List(iElementCount);
    lstFiles.addActionListener(this);
    //set the current directory
    File dir = new File(System.getProperty("user.dir"));
    currentDir = dir;
    listDirectory(dir);
    add(lstFiles);
    addWindowListener(
    new WindowAdapter(){
      public void windowClosing(WindowEvent e){
        System.exit(0);
      }

    } );


  }

  public  void actionPerformed(ActionEvent e){
    int i = lstFiles.getSelectedIndex();
    if(i==iRootElement){
      upDir(currentDir);
    }else{
    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);
    if(fCurFile.isDirectory()){
         listDirectory(fCurFile);
          }
    }
       
  }
  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.remove(iRootElement);
      lstFiles.add(" "+File.separator+" ",iRootElement);
      return;
    }else{
      File fparent = new File(sparent);
      listDirectory(fparent);
    }
  }
  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.removeAll();
    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]);
       if(curFile.isDirectory()){
          sFileName = "[dir ]" + safiles[i];
          }else{
            sFileName = "[file]"+safiles[i]; 
        }
      lstFiles.addItem(sFileName);
    }
    add(lstFiles);
  currentDir=dir; 
  }
    
}

Questions

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();


Answers


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

http://metalab.unc.edu/javafaq/books/javaio/index.html

This topic is covered in the Sun Tutorial at
http://java.sun.com/docs/books/tutorial/essential/io/

The Java API on the File class at Sun
http://java.sun.com/products/jdk/1.2/docs/api/java/io/File.html

The JLS on Java IO a bit academic and bare
http://www.infospheres.caltech.edu/resources/langspec-1.0/javaio.doc.html

Richard Baldwin on I/O
http://home.att.net/~baldwin.rg/Intermediate/Java060.htm

Joyothi has some handy tables for the I/O classes at
http://www.geocities.com/SiliconValley/Network/3693/io.html

Last updated
24 Oct 2000
copyright © Marcus Green 2000
most recent version at www.jchq.net