将文件名添加到 Path 对象

Add a file name to a Path object

我有一个指向文件夹的 Path 对象。

Path pathToFolder = Paths.get( "/Users/someuser/" );

...或使用 Path.of 的推荐方式:

Path pathToFolder = Path.of( "/Users/someuser/" );

我想在该文件夹中使用 Files.newBufferedWriter 创建一个名为 "whatever.text" 的文件,我在其中传递了一个 Path 对象。

BufferedWriter writer = Files.newBufferedWriter( pathToFile ) ;

如何转换我的 pathToFolder 以获得 Path 对象 pathToFile

我需要的不仅仅是字符串操作,因为这些是在运行时确定的软编码值。我也在尝试跨平台。

这似乎是一个显而易见的问题,但我找不到任何现有的 post(术语确实使搜索变得棘手)。

您正在寻找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".

所以你应该使用这个:

Path pathToFolder = Path.of("/Users/someuser/");
Path pathToFile = pathToFolder.resolve("your-file-name");
BufferedWriter writer = Files.newBufferedWriter(pathToFile);