When working with files in Java, it is often necessary to convert absolute file paths to relative file paths.
This is especially useful when working with files that may be moved to different locations, or when working with files that need to be accessed from different locations.
To get the relative path from two absolute paths in Java, we can use the Path
class, which is part of the java.nio.file
package.
The Path
class provides a number of methods for working with file paths, including the relativize()
method, which we will use in our program.
Here is the Java program to get the relative path from two absolute paths:
import java.nio.file.*; public class GetRelativePath { public static void main(String[] args) { // Define two absolute file paths Path path1 = Paths.get("C:\\Users\\John\\Documents\\file1.txt"); Path path2 = Paths.get("C:\\Users\\John\\Desktop\\file2.txt"); // Get the relative path between the two paths Path relativePath = path1.relativize(path2); // Print the relative path System.out.println(relativePath); } }
In this program, we start by importing the java.nio.file
package, which contains the Path
class. We then define two absolute file paths using the Paths.get()
method.
Next, we use the relativize()
method of the Path
class to get the relative path between the two absolute paths.
This method returns a Path
object representing the relative path between the two paths.
Finally, we print the relative path using the System.out.println()
method.
Note that the relativize()
method requires that both paths be either absolute or relative.
If one path is absolute and the other is relative, the method will throw an IllegalArgumentException
.
In conclusion, getting the relative path from two absolute paths in Java is a straightforward task using the Path
class from the java.nio.file
package.
This allows us to easily work with files in a platform-independent way, and to handle file paths that may be located in different locations.