Friday, 8 August 2014

Difference between getPath(), getCanonicalPath() and getAbsolutePath() of File in Java

File API is very important one in Java, it gives access of File system to Java programs. Though Java's file API is rich, there are lot of subtleties to know when you use them. One of the common query programmer's has about file path is difference between getPath(), getCanonicalPath() and getAbsolutePath() methods, why there are three methods to get file path and what happens if you call getPath() in place of getCanonicalPath(). By the way, before understanding difference between getPath(), getAbsolutePath() and getCanonicalPath() let's understand the concept behind this methods, i.e. difference between path, absolute path, and canonical path. In general, a path is way to get to a particular file or directory in a file system, it can be absolute (also known as full path) or relative e.g. relative to current location. Absolute path defines path from root of the file system e.g. C:\\ or D:\\ in Windows and from / in UNIX based operating systems e.g. Linux or Solaris. Canonical path is little bit tricky, because all canonical path is absolute, but vice-versa is not true. It actually defines a unique absolute path to the file from root of the file system. For example, C://temp/names.txt is a canonical path to names.txt in Windows, and /home/javinpaul/test/names.txt is canonical path in Linux. On the other hand, there can be many absolute path to the same file, including the canonical path which has just seen. For example another absolute path to the same file  in Windows can be C://temp/./names.txt; similarly in UNIX /home/javinpaul/test/./names.txt is another absolute path to the same file. So you can say that, absolute path may contain meta characters like . and .. to represent current and parent directory. In rest of this article, we will learn difference between getPath(), getAbsolutePath() and getCanonical() Path by looking at values it return for a particular file.

No comments:

Post a Comment