Java Files  «Prev  Next»


Lesson 4Listing File information
ObjectiveExplore whether a File object exists and what its name is.

File Listing Information in Java

Once you have a File object in place, you will probably want to get information about the object. There are a number of methods you can use to get this information and in the next 3 lessons, we will look at examples of using these methods. Then, you will have a chance to write a program that lists all the information about a given file.
Two important pieces of information you will need about a File object are
  1. whether the object exists, and
  2. if it does exist, what is the name of the object?

Does the File object exist?

Since a File object does not necessarily correspond to a real file on the disk, the first question you should ask is whether the file actually exists. The exists() method indicates whether or not a particular file exists where you expect it to be.
Question: You have to ask yourself one question.
Does the file actually exist?

public boolean exists()

What's the object's name?

Once you are assured the File object exists, the most basic question you can ask a file is "What is your name?" You do this with the getName() method, which takes no arguments and returns a string.
Hello File, you and I have not been formally introduced, but I really want to get to know you better.
Question: What is your name?
Artificial intelligence response: Well, if you really want to know my name, you will have to use the getName() method that returns a String. (See below)

public String getName()

The string returned is just the name of the file. It does not include any piece of the directory or directories that contain this file.
In other words you get back file1 instead of

/home/users/glenngould/file1
which represents the complete path.