Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java nio: How to add extension to an absolute path?

Tags:

java

path

nio

This feels like it should be something straight forward, but I can seem to find an elegant solution to it without converting to File.

Given a Path

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

How to do get the path /a/b/foo.bar? subpath will return a relative path regardless of whether the original path is relative or absolute.

I would prefer not to have to use additional libraries. But, maybe that is the only way?

like image 902
jm1234567890 Avatar asked Oct 22 '15 04:10

jm1234567890


People also ask

How do you declare an absolute path in Java?

A path is either relative or absolute. An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.

What is import Java NIO file paths?

Technically in terms of Java, Path is an interface which is introduced in Java NIO file package during Java version 7,and is the representation of location in particular file system.As path interface is in Java NIO package so it get its qualified name as java. nio. file.


1 Answers

To change the file name of a Path, use one of the resolveSibling() methods:

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.

So, to add extension ".bar" to a Path:

path = path.resolveSibling(path.getFileName() + ".bar"); 
like image 92
Andreas Avatar answered Sep 22 '22 21:09

Andreas