如果我知道文件名,有没有一种简单的方法获取文件路径?
您可以使用 Path
API:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
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"
File path
更改为 String path
。 - Ascalonian您可以使用:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
或者
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
这将返回根文件夹路径,无需使用文件名。然后您可以向下钻取到您想要的位置。
例如:/src/main/java...