File Dialogs  «Prev  Next»


Lesson 6Get Directory and Filename
ObjectiveObtain the Directory and Filename

Get Directory and Filename

Write Program that allows the user to select File

from a file dialog box and then write the file to System.out.
After making the file dialog box visible, you find out what file the user chose by using the FileDialog class's getDirectory() and getFile() methods. Use these two strings to create a new File object.

Here is an example of using the getDirectory and getFile methods:

FileDialog fd = new FileDialog(new Frame(), 
"Please choose a file:", FileDialog.LOAD);
fd.setVisible(true);
File f = new File(fd.getDirectory(), fd.getFile());

If the user clicks the Cancel button, getFile() and getDirectory() return null. You should be ready to catch this, or you will get a NullPointerException.

Choosing Files with FileDialog Boxes - Exercise

Click the Exercise link below to write a program that allows the user to select a file from a file dialog box and then write the file to System.out.
Choosing Files with FileDialog Boxes - Exercise