Working with the File Object: an overview

A Java `File` object points at a path so you can inspect it; creating one does not open the file.

Apprentice · Java · Updated

By

Java provides a File object to help us in working with the file system. The File object allows us to inspect a path in the file system.

File file = new File("/Users/john/documents/homework.txt");

In this example the file variable has a reference to the path of a file named homework.txt.

It is important to note that this line of code DOES NOT open the file at that path. This is simply a reference to that path and allows us to inspect that path. In fact the file homework.txt may not even exist.

Do it: tell absolute paths from relative ones

The grade book app lets teachers type where their grade file is. Before it makes a File for that path, it wants to know which kind of path it was given, so it can tell the teacher where it will look: an absolute path says exactly where the file is, from the top of the drive; a relative one is looked up from the folder the app runs in.

An absolute path starts in one of two ways:

  • on a Mac or Linux, with a slash: /Users/john/documents/homework.txt;
  • on Windows, with a drive: a letter and a colon, such as C:\Users\john\homework.txt. So the colon is the second character, at index 1.

A relative path, such as homework.txt or data/orders.txt, does neither.

The method gets one value:

  • path: a path, as the teacher typed it. It always has at least two characters.

For example:

path Starts with /? Colon at index 1? Absolute?
/Users/john/documents/homework.txt Yes No true
C:\Users\john\homework.txt No Yes true
homework.txt No No false

So isAbsolute("/Users/john/documents/homework.txt") returns true.

Your job: write the method isAbsolute(String path) so it returns a boolean.

  • Return true when the path starts with /.
  • Return true when the path's first colon is at index 1.
  • Return false otherwise.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets