Get Absolute File Path of a File in Java
Tags: Java File Java IO Java NIO
Introduction
In this post we will explore how to get an absolute path of a file in a Java application and return it as a String value.
Using Java NIO Path.toAbsolutePath() method
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathToAbsolutePathExample {
public static void main(String... args) {
String fileName = "simple-solution-logo.png";
Path path = Paths.get(fileName);
Path absolutePath = path.toAbsolutePath();
String absoluteFilePath = absolutePath.toString();
System.out.println(absoluteFilePath);
}
}
D:\SimpleSolution\simple-solution-logo.png
Using Java IO File.getAbsolutePath() method
import java.io.File;
public class FileGetAbsolutePathExample {
public static void main(String... args) {
String fileName = "simple-solution-logo.png";
File file = new File(fileName);
String absoluteFilePath = file.getAbsolutePath();
System.out.println(absoluteFilePath);
}
}
D:\SimpleSolution\simple-solution-logo.png
Happy Coding 😊