[英]Get the filePath from Filename using Java
如果我知道文件名,是否有一種簡單的方法來獲取文件路徑?
您可以使用Path
api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
查看java.io.File 類中的方法:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
我不確定我是否完全理解你,但如果你想獲得絕對文件路徑,前提是你知道相對文件名,你總是可以這樣做:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
File 類還有幾個您可能會覺得有用的方法。
使用“文件”類的正確解決方案以獲取目錄 - 文件的“路徑”:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
這將返回:
path = "C:\\Temp\\your directory"
您可以使用:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
要么
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
這將為您提供根文件夾路徑,而無需使用文件名。 然后,您可以深入到您想去的地方。
示例: /src/main/java...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.