简体   繁体   English

Java nio:如何将扩展添加到绝对路径?

[英]Java nio: How to add extension to an absolute path?

This feels like it should be something straight forward, but I can seem to find an elegant solution to it without converting to File . 这感觉它应该是直截了当的东西,但我似乎可以找到一个优雅的解决方案,而无需转换为File

Given a Path 给定一条Path

Path path = Paths.get("/a/b/foo")

How to do get the path /a/b/foo.bar ? 怎么办路径/a/b/foo.bar subpath will return a relative path regardless of whether the original path is relative or absolute. 无论原始路径是相对路径还是绝对subpath都将返回相对路径。

I would prefer not to have to use additional libraries. 我宁愿不必使用额外的库。 But, maybe that is the only way? 但是,也许这是唯一的方法?

To change the file name of a Path , use one of the resolveSibling() methods: 要更改Path的文件名,请使用resolveSibling()方法之一:

This is useful where a file name needs to be replaced with another file name. 在需要用其他文件名替换文件名的情况下,这很有用。

Using this method ensures that the result Path object is for the same FileSystem as the source Path object. 使用此方法可确保结果Path对象与源Path对象用于相同的FileSystem

So, to add extension ".bar" to a Path : 因此,要将扩展名".bar"添加到Path

path = path.resolveSibling(path.getFileName() + ".bar");

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

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