在 Java 中检索文件的路径

File.getAbsolutePath() 方法返回文件的完整路径(路径 + 名称)的名称。

示例:

File file = File(C:\\Dossier_111\\fichier.txt”);
System.out.println(路径:” + file.getAbsolutePath());
它将显示完整路径:C:\\Dossier_111\\fichier.txt”.

在大多数情况下,您只需要使用 substring() 和 lastIndexOf() 等函数检索没有文件名的路径.

File file = File(C:\\文件111\\fichier.txt);
字符串 absolutePath = file.getAbsolutePath();
String filePath = absolutePath.
substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println(路径:” + filePath);
Runtime:

C:\\Folder111

Resources:
tutorialspoint - Java.io.File.getAbsolutePath() 方法


Commentaires (12)

Connectez-vous pour commenter

Rejoignez la discussion et partagez vos connaissances avec la communauté

JD
Jean Dupont Il y a 2 heures

Excellent tutoriel !

👍 12 Répondre Signaler
CodeurJava ✓ Auteur • Il y a 1 heure

N'hésitez pas si vous avez des questions.