简体   繁体   English

用Java处理命令行文件路径参数的最佳方法

[英]Best way to process command line file path argument in Java

I'd like to pass a file path argument to my application in a relative form, eg ~/test.conf or ../test.conf , but i can't get a proper full file path, though i've tried it with old java.io and new java.nio Files/Paths . 我想以相对形式(例如~/test.conf../test.conf将文件路径参数传递给我的应用程序,但是尽管尝试了它,但我无法获得正确的完整文件路径使用旧的java.io和新的java.nio Files/Paths Is there a general way to get a resolved file path without large amount of code? 有没有一种通用的方法来获取无需大量代码的已解析文件路径? It would be fine for the solution to work only in unix envs like OsX or Debian. 该解决方案仅在OsX或Debian之类的unix env中有效。

Update 更新

With a provided argument like ~/test.conf in case of getAbsolutePath it returns a path with a prefixed current folder - /Users/currentUser/Projects/Personal/TestProject/~/text.conf . getAbsolutePath情况下,使用~/test.conf类的提供的参数返回带有前缀的当前文件夹的路径-/ /Users/currentUser/Projects/Personal/TestProject/~/text.conf ~/test.conf /Users/currentUser/Projects/Personal/TestProject/~/text.conf Canonical path returns the same. 规范路径返回相同。

The hard bit here is dealing with POSIX home directories, and sure you deal with ~otheruser/dir/test.conf too (if you want to do it properly). 这里的难点是处理POSIX主目录,并确保您也处理~otheruser/dir/test.conf (如果您想正确执行的话)。

Luckily that's covered in How to handle ~ in file paths . 幸运的是, 如何在文件路径中处理〜对此进行了介绍。

TL;DR - use something like: TL; DR-使用类似:

path.replace("~/", System.getProperty("user.home") + "/");

Once you've done that, and as others have commented, you can just use standard java.io methods (including getCanonicalPath() ). 完成此操作后,正如其他人所评论的那样,您可以仅使用标准的java.io方法(包括getCanonicalPath() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM