使用Java获取文件名中的文件路径

16

如果我知道文件名,有没有一种简单的方法获取文件路径?


你的意思是你有一个文件名并想获取路径吗?如果有很多文件都是这样命名的呢? - m0skit0
是的。我想知道是否有一行代码可以获取已存在文件的路径。我认为我需要搜索目录,然后列出文件。 - user1688404
5个回答

21

您可以使用 Path API:

Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();

我仍在使用Java版本“1.6.0_31”。我认为Path API随Java 1.7一起提供。 - user1688404

18

3
我已经有一个名为'file1.txt'的文件,存储在D:\IM\EclipseWorkspaces\runtime-EclipseApplication\Proj\Software中。如果我执行File file = new File("file1.txt");并获取file.getAbsolutePath,它会给出D:\IM\EclipseVersions\EclipseSDK3_7\file1.txt,这不是我想要的。 - user1688404
2
就像你在帖子下的评论中所说的那样:你无法避免遍历目录。 - jlordo

8

我不确定我完全理解你的意思,但如果您想获取绝对文件路径,只要您知道相对文件名,您总是可以这样做:

System.out.println("File path: " + new File("Your file name").getAbsolutePath());

文件类(File class)还有其他一些方法可能会对您有所帮助。

8

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

String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();

这将返回:

path = "C:\\Temp\\your directory"

getParent() 返回一个字符串。需要将 File path 更改为 String path - Ascalonian
你可以使用getParentFile()函数。 - undefined

0

您可以使用:

FileSystems.getDefault().getPath(new String()).toAbsolutePath();

或者

FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()

这将返回根文件夹路径,无需使用文件名。然后您可以向下钻取到您想要的位置。

例如:/src/main/java...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接