如何访问Java 7 java.nio.file.Path中的子文件/文件夹?
Java 7 引入了 java.nio.file.Path< /a> 作为 java.io.File 的可能的替代品。
使用文件,当我访问特定下的文件时,我会这样做:
File parent = new File("c:\\tmp");
File child = new File(parent, "child"); // this accesses c:\tmp\child
使用路径执行此操作的方法是什么?
我认为这会起作用:
Path parent = Paths.get("c:\\tmp");
Path child = Paths.get(parent.toString(), "child");
但是调用 parent.toString()
看起来很难看。有更好的办法吗?
Java 7 introduced java.nio.file.Path as a possible replacement for java.io.File.
With File, when I access a file under a specific, I would do:
File parent = new File("c:\\tmp");
File child = new File(parent, "child"); // this accesses c:\tmp\child
What's the way to do this with Path?
I supposed this will work:
Path parent = Paths.get("c:\\tmp");
Path child = Paths.get(parent.toString(), "child");
But calling parent.toString()
seems ugly. Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
resolve
方法” rel="noreferrer">Path
。有两种使用此名称的方法。 One 采用相对
Path
和 其他< /a> 一个字符串
。它使用在其上调用的Path
作为父级,并适当地附加String
或相对Path
。Use the
resolve
method onPath
.There are two methods with this name. One takes a relative
Path
and the other aString
. It uses thePath
on which it is called as a parent and appends theString
or relativePath
appropriately.对于任何发现此问题仅专门查找指定路径内的文件的人,您必须了解路径遍历攻击。
请参阅:在Java(或Scala)中过滤向上路径遍历
检查路径是否从根开始是至关重要。
To anyone finding this question looking specifically only for files that are within the specified path, you must be aware of path traversal attacks.
See: Filtering upwards path traversal in Java (or Scala)
It is critical that you check that the path starts with the root.