如何在文件路径中处理〜 [英] How to handle ~ in file paths

查看:116
本文介绍了如何在文件路径中处理〜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的命令行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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆