【Java复杂系统实战经验-2023-08月】Java基础,Path路径计算编码
Java程序设计-个人月报-2023-08月
背景
在本月,给负责的项目做了一次文件存储的迁移工作。
历史原因,开发阶段由于图简便,使用了本地文件存储。
后面经过容器化上云,导致应用出现上传文件分发的多节点的问题。
本项工作的经验,受益于Java基础Path的一些API,颇有收获。
复杂的系统应当构建于通用的,稳定的,有共识的,成熟API之上。 ----沃兹基索德
路径计算
代码中,不要使用路径拼接的原始写法,非常容易出错。例如:
String path = '/bucket/' + projectId + '/v' + version + fileName;
甚至后面直接使用了subString,正则表达式。
这种写法非常不好,当项目内多次使用路径计算的时候,代码复杂性增加。
java.nio.Path
Path path = Paths.get('parent','child');
Path toAbsolutePath()
Returns a Path object representing the absolute path of this path.
File toFile()
Returns a File object representing this path.
Path toRealPath(LinkOption... options)
Returns the real path of an existing file.
这些API非常简单且实用,且不要在代码中试图使用 split("/")
,split(File.pathSeparator)
这类比较初级的写法。
使用Name获取Path中的分片
Path getName(int index)
Returns a name element of this path as a Path object.
int getNameCount()
Returns the number of name elements in the path.
上一级或者下一级
Path getParent()
Returns the parent path, or null if this path does not have a parent.
Path resolve(Path other)
Resolve the given path against this path.
Path resolve(String other)
Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method.
其中 resolve 非常实用:
不用担心,这些路径可以不用存在于本地文件系统上
//你的代码:
path = "a" + "/b";
path = "a/" + "b";
//无法跨平台,且埋下BUG的可能性。
//Path API的代码:
Paths.get("a").resolve("b"); //在Windows上,得出 a\b,在Linux,MacOS上得到 a/b。
从整个路径中获取文件名和后缀
Path getFileName()
Returns the name of the file or directory denoted by this path as a Path object.
//你的old class代码:
String path= "foo/bar/some.pdf";
path.subString(path, path.lastIndexOf("/"));
//搞不好还整出来一个"/some.pdf",需要试试。
//Path API的代码
Paths.get(path).getFileName(); //some.pdf
URI
URI的组成部分是 Schema:// + 剩余部分地址,在某些情况下,例如ClassPath的表示,就非常重要。
URI toUri()
Returns a URI to represent this path.
String path = "/root/foo/bar/slankka.md"
URI uri = Paths.get(path).toUri(); //得到 file:///root/foo/bar/slankka.md
//未经验证,但意思对就行。
理解了上述 java API,org.apache.hadoop.fs.Path 同理。这样在编写大数据相关的Path就不容易出错。
一些例子
file:///root/foo/bar/slankka.md
hdfs://dc1/user/hdfs/foo/bar/slankka.md
viewfs://cluster123/foo/bar/slankka.md
Panel项目
因为考虑到迁移过程中的以外情况,针对迁移功能做了一个Web UI。在前端人手不足,工期紧张,且系统变动频繁的情况下,
由单个系统带WebFrontEnd,及时拆分出一个子项目,名称就叫做Panel Project。
示意图
下图就是我画的一个示意图。Panel Project 适合页面快速迭代,适合轻型HTTP Client,适合后端人员使用模板引擎。
具体就随时可以孵化成一个成熟的项目。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!