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

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

How to get classpath resources by extension?

问题

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

/a/b/c/x1.txt
/a/b/d/x2.txt
/a/b/e/x3.txt

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

英文:

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

/a/b/c/x1.txt
/a/b/d/x2.txt
/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

尝试这样做

    Path path = Paths.get(YourClass.class.getResource("/resources").toURI());

    List<String> result = Files.find(path, 100,
            (p, a) -> p.toString().toLowerCase().endsWith(".txt"))
            .map(Path::toString)
            .collect(Collectors.toList());
英文:

Try this:

Path path = Paths.get(YourClass.class.getResource(&quot;/resources&quot;).toURI());

List&lt;String&gt; result = Files.find(path, 100,
        (p, a) -&gt; p.toString().toLowerCase().endsWith(&quot;.txt&quot;))
        .map(Path::toString)
        .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:

确定