鉴于此类文件路径:
Path filePath; // "/Users/me/Desktop/archive.zip"
我想要一个函数将此文件路径转换为目录路径,方法是删除其文件扩展名,将文件路径视为目录路径。例如。如:
Path dirPath = asDirectoryPath(filePath); // "/Users/me/Desktop/archive"
我试过了什么?
好吧,我有一个解决方案,在我看来有点难看:
private Path asDirectoryPath(Path filePath)
{
return Paths.get(path.toString().substring(0, path.toString().lastIndexOf('.')));
}
为什么难看?因为我被迫执行字符串转换的路径并搜索'。'符号,假设后面的字符是文件扩展名。此功能应该是可移植的,应该可以在windows和unix系统中使用。还有更正确的解决方案吗?谢谢。
这里可以使用正则表达式和split方法。
path.toString().split("\\.")[0])
您可以在java.nio中使用getParent()
的Path
方法,它可以根据需要将Path
用于文件,并将Path
返回到包含该文件的文件夹。如果给定的Path
是文件夹,则返回父文件夹,如果没有父文件夹,则返回null。
Path dirPath = filePath.getParent();
你的方法应该是这样的
private Path asDirectoryPath(Path filePath) {
return Paths.get(filePath.getParent());
}