java - 将文件名添加到 Path 对象

标签 java path filenames

我有一个 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/

相关文章:

java - 无法在Linux上为Java程序正确设置PATH变量

python - 导入错误 : No module named path

linux - 如何使用终端重命名文件

windows - 在 Windows 上更改文件大小写?

java - .NET Core 2.0 成就

java - ANDROID - 如何将 JSONArray 显示到 TextView 中

java - maven资源插件错误

python - os.path.join() 是如何工作的?

java - 为什么初始化数组的时间不同

iphone - 如何获取存储在 NSDocumentDirectory 中的文件的名称?