I have a Path
object leading to a folder.
Path pathToFolder = Paths.get( "/Users/someuser/" );
…or the recommended way using Path.of
:
Path pathToFolder = Path.of( "/Users/someuser/" );
I want to create a file named "whatever.text" in that folder using Files.newBufferedWriter
where I pass a Path
object.
BufferedWriter writer = Files.newBufferedWriter( pathToFile ) ;
How do I transform my pathToFolder
to get a Path
object pathToFile
?
I need more than mere string manipulation, as these are soft-coded values determined at runtime. And I am trying to be cross-platform as well.
This seems like an obvious question, but I could not find any existing post (the terminology does make searching tricky).
Path.resolve
You are looking for Path.resolve()
:
Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method. For example, suppose that the name separator is "/" and a path represents "foo/bar", then invoking this method with the path string "gus" will result in the Path "foo/bar/gus".
So you should use this:
Path pathToFolder = Path.of("/Users/someuser/");
Path pathToFile = pathToFolder.resolve("your-file-name");
BufferedWriter writer = Files.newBufferedWriter(pathToFile);