什么是在Java中使用资源目录的一个好的用例?

huangapple 未分类评论64阅读模式
标题翻译

What would be a good use case of using resources directory in Java?

问题

当我想要从文件系统加载文件或资产(比如一张图片)到我的程序中时,我可以直接从文件系统中读取文件,使用类似以下的方式:

Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);

或者将文件作为资源加载,使用类似以下的方式:

getClass().getClassLoader().getResourceAsStream(fileName);

在 Javadoc 中,Class#getResource() 方法的文档中指定:在命名模块中的资源受到封装规则的影响,这些规则在 {@code Module} 的 {@link Module#getResourceAsStream getResourceAsStream} 方法中进行了说明,因此当资源是非“{@code .class}”资源且所在的包对调用者模块不可开放时,该方法返回 {@code null},但是我在某种程度上无法理解在我何时决定将文件作为资源加载或者仅从文件系统中读取。

英文翻译

When I want to load a file or asset(say an image) from file system into my program, I could either read the file directly from file system using something like

Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);

vs loading the file as a resource

getClass().getClassLoader().getResourceAsStream(fileName);

In Javadoc, Class#getResource() method, Javadoc specifies Resources in named modules are subject to the rules for encapsulation specified in the {@code Module} {@link Module#getResourceAsStream getResourceAsStream} method and so this method returns {@code null} when the resource is a non-"{@code .class}" resource in a package that is not open to the caller's module. but I somehow could not wrap my head around what would be the deciding factor for me to load a file as a resource or simply read it from file system.

huangapple
  • 本文由 发表于 2020年3月4日 03:05:37
  • 转载请务必保留本文链接:https://java.coder-hub.com/60513977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定