如何按扩展名获取类路径资源?

huangapple go评论92阅读模式
英文:

How to get classpath resources by extension?

问题

假设我在类路径中有一些资源文件:

  1. /a/b/c/x1.txt
  2. /a/b/d/x2.txt
  3. /a/b/e/x3.txt

我的代码并不知道这些资源文件的完整路径,它只知道它们的扩展名 .txt
您会如何编写一个函数来返回具有扩展名 .txt 的资源文件的路径?

英文:

Suppose I've got a few resource files in my classpath:

  1. /a/b/c/x1.txt
  2. /a/b/d/x2.txt
  3. /a/b/e/x3.txt

My code does not know the full paths of these resource files. It knows only their extension .txt.
How would you write a function to return the paths of the resources with extension .txt ?

答案1

得分: 2

  1. 尝试这样做
  2. Path path = Paths.get(YourClass.class.getResource("/resources").toURI());
  3. List<String> result = Files.find(path, 100,
  4. (p, a) -> p.toString().toLowerCase().endsWith(".txt"))
  5. .map(Path::toString)
  6. .collect(Collectors.toList());
英文:

Try this:

  1. Path path = Paths.get(YourClass.class.getResource(&quot;/resources&quot;).toURI());
  2. List&lt;String&gt; result = Files.find(path, 100,
  3. (p, a) -&gt; p.toString().toLowerCase().endsWith(&quot;.txt&quot;))
  4. .map(Path::toString)
  5. .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年4月11日 03:51:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/61147708.html
匿名

发表评论

匿名网友

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

确定