A file system stores and organizes files on some form of media, generally one or more hard drives. Most file systems have a tree or hierarchial structure. At the top of the tree is one (or more) root nodes. Under the root node, there are files and directories.
Path is defined as the route from the root node to the target file or folder. Paths can be
Relative or
Absolute.
Symbolic LinksThese are also referred to as a
symlink or a
soft link, in short. A
symbolic link is a special file that serves as a reference to another file. In normal words, it is a substitute to a long file name that includes the path. Symbolic links are transparent to applications, and operations on symbolic links are automatically redirected to the target of the link.
The Path Class
The
Path class, is introduced in the JDK7 release belongs to the
java.nio.file package. As its name implies, the
Path class is a programmatic representation of a path in the file system. A
Path oject contains the file name and directory list used to construct the path.
The
Path class offers many features, that fall in either of the 2 categories.
- Path operations
- File operations
Path Operations
The Path class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path.
Creating a Path: A Path instance contains the information used to specify the location of a file or directory. A
Path can easily be creating by using one of the following get methods:
Path p1 = Paths.get("/tmp/foo");
Path p2 = Paths.get(args[0]);
Path p3 = Paths.get("file:///Users/joe/FileTest.java");
Retrieving Information about a PathDifferent information about a path can be known by using some methods given below:
- toString
- getName
- getNameCount
- subpath
- getParent
- getRoot
- isHidden
Path ConversionsA
Path can be converted into many different forms with simple method calls. For example, to convert it into a string that can be opened from a browser, you can use
toUrl().
toAbsolutePath method returns a
Path object that is an absolute path of the given input.
The
toRealPath method returns the
real path of an existing file. This method performs several operations in one:
- If true is passed to this method and the file system supports symbolic links, this method resolves any symlinks
- If the Path is relative, it returns an absolute path
- If the Path contains any redundant elements, it returns a path with those elements removed.
Joining Two Paths with by using the
resolve() method.
Creating a Path Between Two Paths using the
relativize() method. The new path created will be
relative to the original path.
File Operations
The
Path class offers a rich set of methods for reading, writing and manipulating files and directories.
Catching ExceptionsWith file I/O, unexpected conditions are a fact of life: a file exists when expected, the program doesn't have access to the file system, the default file system implementation does not support a particular function, and so on.
All the methods that access the file system can throw an
IOException. It is best practice to catch these exceptions by embedding these methods into a
try block and to catch any exceptions in a
catch bock. If in a program any streams or channels are opened then you should close them in a
finally block.
VarargsIt stands for
Variable Arguments. Several
Path methods accept an arbitrary number of arguments when flags are specified. For example:
Path moveTo(Path, CopyOption...)
When a method accepts a varargs argument, you can pass it a comma-separated list of values or an array(CopyOption[]) of values.
Atomic OperationsSeveral
Path methods, such as
moveTo, can perform certain operations atomically in some file systems.
Method ChainingMany of the I/O methods support the concept of
method chaining. You first invoke a method that returns an object. You then immediately invoke a method on that object, which returns yet another object, and so on.
FileRef InterfaceThe
Path class implements the
FileRef interface. The
FileRef interfacce includes methods for locating a file and accessing that file.
What is a Glob2 methods in the
Path class accept a glob argument, but what is a glob?
A glob pattern is specified as a string and is matched against other strings, such as directory or file names. Glob syntax follows several simple rules:
- An asterik, *, matches any number of characters
- 2 asterisks, **, workds like * but crosses directory boundaries.
- A question mark, ?, matches exactly one character.
- Braces specify a collection of subpatterns. For example:
- {sun,moon,stars} matches "sun","moon", or "stars."
- {temp*,tmp*} matches all strings beginning with "temp" or "tmp"
- Square brackets convey a set of single characters or a range of characters when hyphen(-) is used:
- [aeiou] matches any lowercase vowel.
- [0-9] matches any digit.
- [A-z] matches any uppercase letter
- [a-z,A-Z] matches any uppercase or lowercase letter
- All other characters match themselves
- To match *, ? or other special characters, you can escape them by using the backlash character.
Checking File AccessibilityTo check the existence of a file or in which mode the file is opened, you can use the
checkAccess(AccessMode...) method. The varargs argument can be any combination of the
AccessMode options, that is,
Read,
Write &
ExecuteDeleting a File or DirectoryThis operation can be performed using the
delete method. It throws an exception if the deletion fails. The
deleteIfExists method deletes only if a file exists. Hence it does not throw the
NoSuchFileException.
Copying a File or DirectoryYou can copy a file or directory by using the
copyTo method. This method takes a varargs argument.
Moving a File or DirectoryYou can move a file or directory by using the
moveTo method. This method takes a varargs argument.
There are many other manipulative methods in the Path class, which are given below:tutorials