Constructing a Filename Path
A File object is used to represent a filename. Creating the File object has no effect on the file system; the filename need not exist nor is it created.
On Windows, this example creates the path /a/b. On Unix, the path would be /a/b.
String path = File.separator + "a" + File.separator + "b";
Converting Between a Filename Path and a URL
// Create a file object
File file = new File("filename");
// Convert the file object to a URL
URL url = null;
try {
// The file need not exist. It is made into an absolute path
// by prefixing the current working directory
url = file.toURL();
// file:/d:/almanac1.4/java.io/filename
} catch (MalformedURLException e) {
}
// Convert the URL to a file object
file = new File(url.getFile()); // d:/almanac1.4/java.io/filename
// Read the file contents using the URL
try {
// Open an input stream
InputStream is = url.openStream();
// Read from is
is.close();
} catch (IOException e) {
// Could not open the file
}
Getting an Absolute Filename Path from a Relative Filename Path
File file = new File("filename.txt");
file = file.getAbsoluteFile(); // c:/temp/filename.txt
file = new File("dir"+File.separatorChar+"filename.txt");
file = file.getAbsoluteFile(); // c:/temp/dir/filename.txt
file = new File(".."+File.separatorChar+"filename.txt");
file = file.getAbsoluteFile(); // c:/temp/../filename.txt
// Note that filename.txt does not need to exist
Determining If Two Filename Paths Refer to the Same File
A filename path may include redundant names such as `.' or `..' or symbolic links (on UNIX platforms). File.getCanonicalFile() converts a filename path to a unique canonical form suitable for comparisons.
File file1 = new File("./filename");
File file2 = new File("filename");
// Filename paths are not equal
boolean b = file1.equals(file2); // false
// Normalize the paths
try {
file1 = file1.getCanonicalFile(); // c:/almanac1.4/filename
file2 = file2.getCanonicalFile(); // c:/almanac1.4/filename
} catch (IOException e) {
}
// Filename paths are now equal
b = file1.equals(file2); // true
Getting the Parents of a Filename Path
// Get the parent of a relative filename path
File file = new File("Ex1.java");
String parentPath = file.getParent(); // null
File parentDir = file.getParentFile(); // null
// Get the parents of an absolute filename path
file = new File("D://almanac//Ex1.java");
parentPath = file.getParent(); // D:/almanac
parentDir = file.getParentFile(); // D:/almanac
parentPath = parentDir.getParent(); // D:/
parentDir = parentDir.getParentFile(); // D:/
parentPath = parentDir.getParent(); // null
parentDir = parentDir.getParentFile(); // null
Determining If a Filename Path Is a File or a Directory
File dir = new File("directoryName");
boolean isDir = dir.isDirectory();
if (isDir) {
// dir is a directory
} else {
// dir is a file
}