如何在文件路径中处理〜 [英] How to handle ~ in file paths
问题描述
我正在编写一个简单的命令行Java实用程序。我希望用户能够使用〜
运算符传递相对于其主目录的文件路径。所以类似〜/ Documents /...
I'm writing a simple command line Java utility. I would like the user to be able to pass in a file path relative to their home directory using the ~
operator. So something like ~/Documents/...
我的问题是有没有办法让Java解决这个问题路径类型自动?或者我是否需要扫描〜
运算符的文件路径?
My question is is there a way to make Java resolve this type of path automatically? Or do I need to scan the file path for the ~
operator?
似乎应该将这种类型的功能烘焙到文件
对象中。但它似乎不是。
It seems like this type of functionality should be baked into the File
object. But it doesn't seem to be.
推荐答案
一个简单的 path = path.replaceFirst(^ 〜,System.getProperty(user.home));
何时从用户处获取(在使用文件
之前) )应该足以在大多数情况下工作 - 因为如果它是路径的目录部分中的第一个字符,则只扩展到主目录。
A simple path = path.replaceFirst("^~", System.getProperty("user.home"));
when it is gotten from the user (before making a File
out of it) should be enough to work in most cases - because the tilde is only expanded to a home directory if it is the first character in a directory section of a path.
这篇关于如何在文件路径中处理〜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!