Overview
Nearly all programs require the ability to transfer data in and out of memory. For example, data may be stored on disk or sent over a network.
Java provides many classes that make "I/O" (input and output) relatively easy and platform independent. In this lesson, you will learn how to act upon the file structure of a platform from inside a Java application. Note that Java applets are NOT permitted to access a platform's file structure for security reasons.
The File class
Is part of the java.io package. You will need an import statement to access the class with its abbreviated name.
Is an extension of the Object class
Object
\
File
Encapsulates platform-independent information about a file or a directory.
While all platforms use pathname strings to name files and directories, they do not agree on the format of these strings. For example, the Windows pathname string is not the same as the Unix pathname string.
Regardless of platform, however, all pathnames have two components:
An optional system-dependent prefix string (such as the disk-drive specifier followed by "/" for the Unix root directory or "\" for the Windows root directory)
A sequence of zero or more string names where each name, except for the last, denotes a directory. The the last name may denote either a directory or a file. A system-dependent separator ("/" for Unix or "\" for Windows) is used between each name.
For example, the following represents a valid Windows pathname:
C:\My Documents\New Courses\Lesson55.htm
Regardless of the platform, the File class presents a system-independent view of pathnames.
Has a number of static fields. These two are the most useful:
Field
Usage
separator
The String representation of the filename separator used on the current platform.
separatorChar
The char representation of the filename separator used on the current platform.
For example, the following program can determine if it is running under Windows:
import java.io.*;
public class App {
public static void main(String[] args) {
if (File.separator.equals("\\"))
System.out.println("Windows");
else
System.out.println("Not Windows");
}
}Note that the double backslash is required to because a single backslash denotes an escape sequence.
NOTE: Constructing a File object does NOT create a disk file. It only constructs a platform-independent object for referencing the file.File f = new File("C:\\My Documents\\Misc\\Resume.doc");
Method
Usage
createNewFile()
Atomically creates a new, empty file named by this pathname if and only if a file with this name does not yet exist
delete()
Deletes the file or directory denoted by this pathname
exists()
Tests whether the file denoted by this pathname exists
getName()
Returns the name of the file or directory denoted by this pathname
getParent()
Returns the pathname of this pathname's parent, or null if this pathname does not name a parent directory
getPath()
Returns the pathname string of this pathname
isDirectory()
Tests whether this pathname is a directory
isFile()
Tests whether this pathname is a file
lastModified()
Returns the time that the file denoted by this pathname was last modified
length()
Returns the length of the file denoted by this pathname
list()
Returns an array of strings naming the files and directories in the directory denoted by this pathname
mkdir()
Creates the directory named by this pathname
renameTo()
Renames the file denoted by this pathname
Consult the Java API documentation for more details.
The FileDialog class
Is part of the java.awt package. You will need an import statement to access the class with its abbreviated name.
Has many ancestor classes as indicated by the following diagram:
Object
\
Component
\
Container
\
Window \
Dialog \
FileDialog
Can be instantiated to display a modal dialog window from which the user can select a file. Because it is a modal dialog, once an application makes a FileDialog object visible, it cannot continue until the user has chosen a file.
Has two static fields that indicate whether the file will be used for input or output. They are
Field
Usage
LOAD
Indicates that the purpose of the file dialog window is to locate a file from which to read
SAVE
Indicates that the purpose of the file dialog window is to locate a file to which to write
FileDialog fd = new FileDialog(this, "Choose file", FileDialog.LOAD);
fd.setVisible(true);which constructs and displays a file dialog window for the current (this) object. The title of the file dialog window will be "Choose file", and the chosen file will be used for input.
Method
Usage
getDirectory()
Returns a String representing the directory of the selected file
getFile()
Returns a String representing the filename of the selected file
setDirectory()
Sets the directory of this file dialog window to be the specified directory
setFile()
Sets the selected file for this file dialog window to be the specified file
Consult the Java API documentation for more details.
Sample program
The following menu-driven, Windows program uses the File and FileDialog classes to display a variety of information about a file selected by the user:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class App extends Frame implements ActionListener {
// Object references.
MenuBar mainBar;
Menu fileMenu;
MenuItem find;
MenuItem exit;
TextArea fileInfo;
// Processing starts here.
public static void main(String[] args) {
App myWindow = new App("File Analyzer");
myWindow.setSize(500, 200);
myWindow.setVisible(true);
}
// Class constructor.
public App(String title) {
// Usual boilerplate for startup and shutdown.
super(title);
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
}
);
// Create the frame's menu bar.
mainBar = new MenuBar();
setMenuBar(mainBar);
fileMenu = new Menu("File");
find = new MenuItem("Find");
find.addActionListener(this);
fileMenu.add(find);
fileMenu.addSeparator();
exit = new MenuItem("Exit");
exit.addActionListener(this);
fileMenu.add(exit);
mainBar.add(fileMenu);
// Create the file information text area.
fileInfo = new TextArea("\n\tUse the menu bar to find a file...",
10, 40, TextArea.SCROLLBARS_NONE);
fileInfo.setFont(new Font("Monospaced", Font.PLAIN, 12));
fileInfo.setEditable(false);
add(fileInfo);
}
// Required method of the ActionListener interface.
public void actionPerformed(ActionEvent e) {
// If the user selected "File" | "Find" from the menu, let them
// choose a file to be analyzed. Then, display its information.
if (e.getSource().equals(find)) {
// Create and display a modal file dialog box through which the
// user can choose the file they want to analyze.
FileDialog fd = new FileDialog(this, "Choose file", FileDialog.LOAD);
fd.setVisible(true);
// Construct a File object for the file the user selected.
File f = new File(fd.getDirectory() + File.separator + fd.getFile());
// Display information about the file the user selected.
fileInfo.setText("\n\t\t\tFILE INFORMATION\n");
fileInfo.append("\n Path: " + f.getPath());
fileInfo.append("\n Directory: " + fd.getDirectory());
fileInfo.append("\n File: " + f.getName());
fileInfo.append("\n Last modified: " +
new Date(f.lastModified()).toString());
fileInfo.append("\n Byte length: " + f.length());
fileInfo.setCaretPosition(0);
}
// If the user selected "File" | "Exit" from the menu, terminate
// the application.
if (e.getSource().equals(exit)) {
dispose();
System.exit(0);
}
}
}
Looking ahead
While the File and FileDialog classes allow a program to act upon the file structure of a platform, they do NOT allow for the actual storage and retrieval of data. That is covered in the next lesson.
Lab exercise for Ferris students
E-mail your answers to this assignment no later than the due date listed in the class schedule.
Review questions
Which one of the following will create and display a file dialog window to assist the user in selecting a file to be used for output?
FileDialog x = new FileDialog(this, "Output file", FileDialog.SAVE);
x.setVisible(true);FileDialog x = new FileDialog(this, "Output file", FileDialog.SAVE);
FileDialog.show(x);FileDialog x = new FileDialog(this, "Output file", FileDialog.SAVE);
x.show();FileDialog x = new FileDialog(this, "Output file", FileDialog.OUTPUT);
x.setVisible(true);FileDialog x = new FileDialog(this, "Output file", FileDialog.OUTPUT);
x.show();
Assuming that all unseen code is correct and that drive D: is a valid drive specification on the platform, what will happen when an attempt is made to compile and execute the following statements in a Java application? The line numbers are for reference purposes only.
1
2File f = new File("D:\\Temp");
f.mkdir();
a compile error will occur at line 1
a compile error will occur at line 2
the code will compile but a runtime exception will occur
the code will compile and execute to create a file named Temp in the root directory of the disk in drive D:
the code will compile and execute to create a directory named Temp in the root directory of the disk in drive D:
Code an expression to determine the length of a file whose path is: C:\Documents\Temp.doc
True or False: An application thread is allowed to continue processing while the user responds to a visible FileDialog object.
True
False