[Java] Get the file path in Java – Get File Path in Java
To get the path 1 I use the file in Java file.getAbsolutePath();
However, this command gives us the file we get, example: /media/quan/DATA/textfile.txt but sometimes we just want to get /media/quan/DATA. To do this we make the following:
String filePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
Code illustrations:
import java.io.File;
public class GetPath {
public static void main(String[] args) {
File file = new File("/media/quan/DATA/textfile.txt"); // Khai bao file textfile.txt
String absolutePath = file.getAbsolutePath();
System.out.println("Absolute file Path : " + file.getAbsolutePath());
String filePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
System.out.println("File Path : " + filePath);
}
}
Output:
Absolute file Path : /media/quan/DATA/textfile.txt
File Path : /media/quan/DATA



0 responses on [Java] Get the file path in Java – Get File Path in Java