使用Java从Filename获取filePath

use*_*404 6 java file filepath

是否有一种简单的方法来获取filePath我知道文件名?

ass*_*ias 14

你可以使用Pathapi:

Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
Run Code Online (Sandbox Code Playgroud)


jlo*_*rdo 14

查看java.io.File类中的方法:

File file = new File("yourfileName");
String path = file.getAbsolutePath();
Run Code Online (Sandbox Code Playgroud)

  • 我已经有一个文件名'file1.txt',并存储在D:\\ IM \\ EclipseWorkspaces \\ runtime-EclipseApplication \\ Proj \\ Software中,如果文件=新文件(“ file1.txt”) ; 并获得file.getAbsolutePath,它给我D:\\ IM \\ EclipseVersions \\ EclipseSDK3_7 \\ file1.txt。这不是我想要的。 (2认同)
  • 就像您在帖子下的评论中所说的那样:您无法避免遍历目录。 (2认同)

Mil*_*vić 7

我不确定我是否完全理解你,但是如果你希望获得绝对文件路径,只要你知道相对文件名,你就可以这样做:

System.out.println("File path: " + new File("Your file name").getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)

File类还有几个你可能会觉得有用的方法.


Mar*_*kus 6

使用“文件”类的正确解决方案以获取目录 - 文件的“路径”:

String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
Run Code Online (Sandbox Code Playgroud)

这将返回:

path = "C:\\Temp\\your directory"
Run Code Online (Sandbox Code Playgroud)