Absolute file path looks like this --> C:\downloads\file.txt is an absolute path where C is the root node
Relative path is something lik this --> photos\img1.jog.So this path need to be combined with another path that contains the root node.
On windows delimiter is a backslash /, on unix its a forward slash \
We can get a path of a file lying at the root our current project using below example
Path dataPath = FileSystems.getDefault().getPath("data.txt");
Path subDirPath = FileSystems.getDefault().getPath("files","SubDirectoryFile.txt");
printFile(subDirPath);
Path dataPath = Paths.get("C\\MyIdeaProject\\Projects\\data.txt");
We can use the below example to get the absolute or complete path of our working directory of our project.We can then print the path represented by above Path object using toAbsolutePath method.Please note it will append a /. at the end of or project directory
Path filePath = Paths.get(".");
System.out.println(filePath.toAbsolutePath());
Will print C:\myNewProject\Java Paths Basics .
subDirPath = Paths.get(".","files","SubDirectoryFile.txt");
printFile(subDirPath);
outsideDirPath = Paths.get("C:\\","report\\","outthere.txt");
outsideDirPath = Paths.get("C:","/report","/outthere.txt");
printFile(outsideDirPath);
Method to print contents of current file
public static void printFile(Path path){
try(BufferedReader fileReader = Files.newBufferedReader(path)){
String line;
while((line=fileReader.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}