java读取resource目录下文件的方法示例

2025-05-29 0 60

本文主要介绍的是java读取resource目录文件的方法,比如这是你的src目录的结构

?

1

2

3

4

5

6

7

8

9

10

11

12
├── main

│ ├── java

│ │ └── com

│ │ └── test

│ │ └── core

│ │ ├── bean

│ │ ├── Test.java

│ └── resources

│ └── test

│ ├── test.txt

└── test

└── java

我们希望在Test.java中读取test.txt文件中的内容,那么我们可以借助Guava库的Resource类

示例代码如下

?

1

2

3

4

5

6

7

8

9
public class TestDemo {

public static void main(String args[]) throws InterruptedException, URISyntaxException, IOException {

BufferedInputStream bufferedInputStream = (BufferedInputStream) Resources.getResource("test/test.txt").getContent();

byte[] bs = new byte[1024];

while (bufferedInputStream.read(bs) != -1) {

System.out.println(new String(bs));

}

}

}

核心函数就是Resources.getResource,该函数其实封装了下述代码:

?

1

2

3

4

5

6

7

8
public static URL getResource(String resourceName) {

ClassLoader loader = MoreObjects.firstNonNull(

Thread.currentThread().getContextClassLoader(),

Resources.class.getClassLoader());

URL url = loader.getResource(resourceName);

checkArgument(url != null, "resource %s not found.", resourceName);

return url;

}

上述代码的核心逻辑很简单,即通过获取classloader来获取resource文件

如果想引入google的guava库,如果你采用的是maven工程的话,可以在pom.xml中加入下面代码:

?

1

2

3

4

5
<dependency>

<groupId>com.google.guava</groupId>

<artifactId>guava</artifactId>

<version>19.0</version>

</dependency>

总结

以上就是关于java读取resource目录文件的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

原文链接:http://www.kissyu.org/2016/07/23/java读取resource目录下的文件/

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java读取resource目录下文件的方法示例 https://www.kuaiidc.com/118668.html

相关文章

发表评论
暂无评论