我有一个 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
?
我需要的不仅仅是字符串操作,因为这些是在运行时确定的软编码值。我也在尝试跨平台。
这似乎是一个显而易见的问题,但我找不到任何现有的帖子(术语确实让搜索变得棘手)。
最佳答案
您正在寻找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);
关于java - 将文件名添加到 Path 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56796780/