Récupérer le chemin d'un fichier en Java

La méthode File.getAbsolutePath() renvoie le nome du chemin complet du fichier (chemin + nom).

Exemple:

File file = File("C:\\Dossier_111\\fichier.txt");
System.out.println("Chemin: " + file.getAbsolutePath());
Il va afficher le chemin complet : "C:\\Dossier_111\\fichier.txt".

Dans la plupart des cas, vous aurez besoin de récupérer seulement le chemin sans le nom du fichier en utilisant des fonctions comme substring() et lastIndexOf().

File file = File("C:\\Dossier111\\fichier.txt");
String absolutePath = file.getAbsolutePath();
String filePath = absolutePath.
substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("Chemin: " + filePath);
Exécution:

C:\\Dossier111

Ressources:
tutorialspoint - Java.io.File.getAbsolutePath() Method