Comment obtenir le chemin de fichier d'un fichier en Java
LeFile.getAbsolutePath() vous donnera le nom de chemin complet complet (chemin de fichier + nom de fichier) d'un fichier.
Par exemple,
File file = File("C:\\abcfolder\\textfile.txt"); System.out.println("Path : " + file.getAbsolutePath());
Il affichera le chemin complet: «Path : C:\abcfolder\textfile.txt».
Dans la plupart des cas, vous n'aurez peut-être besoin que d'obtenir le chemin du fichier «C:\abcfolder\». À l'aide des méthodessubstring() etlastIndexOf(), vous pouvez extraire facilement le chemin du fichier:
File file = File("C:\\abcfolder\\textfile.txt"); String absolutePath = file.getAbsolutePath(); String filePath = absolutePath. substring(0,absolutePath.lastIndexOf(File.separator));
Obtenir un exemple de chemin de fichier
Dans cet exemple, il crée un fichier temporaire et en imprime le chemin d'accès au fichier.
package com.example.file; import java.io.File; import java.io.IOException; public class AbsoluteFilePathExample { public static void main(String[] args) { try{ File temp = File.createTempFile("i-am-a-temp-file", ".tmp" ); String absolutePath = temp.getAbsolutePath(); System.out.println("File path : " + absolutePath); String filePath = absolutePath. substring(0,absolutePath.lastIndexOf(File.separator)); System.out.println("File path : " + filePath); }catch(IOException e){ e.printStackTrace(); } } }
Résultat
File path : C:\Users\example\AppData\Local\Temp\i-am-a-temp-file69424.tmp File path : C:\Users\example\AppData\Local\Temp