How can I obtain the relative path in Java?
There are various methods to get a relative path in Java. One common method is as follows:
- Retrieve the current working directory.
String currentPath = System.getProperty("user.dir");
- Construct a file object based on the current working directory and a relative path.
String relativePath = "src/main/resources/file.txt";
String currentPath = System.getProperty("user.dir");
String absolutePath = currentPath + File.separator + relativePath;
File file = new File(absolutePath);
Please note that the File.separator in the methods above is the system-specific file separator (being \ on Windows and / on Linux).