java8 ReadResourceFile
时间: 2024-04-07 13:25:08 浏览: 12
在Java 8中,可以使用以下代码来读取资源文件:
```java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadResourceFile {
public static void main(String[] args) {
try {
// 通过类加载器获取资源文件的路径
String filePath = ReadResourceFile.class.getClassLoader().getResource("example.txt").getPath();
// 使用Files类读取文件内容
String content = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码中,我们首先通过`getClassLoader().getResource("example.txt")`方法获取资源文件的路径。这里假设资源文件名为"example.txt",你可以根据实际情况修改。
然后,我们使用`Files.readAllBytes()`方法读取文件的所有字节,并将其转换为字符串。最后,我们将文件内容打印出来。
请注意,上述代码中的异常处理部分只是简单地打印异常信息,你可以根据实际需求进行适当的处理。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)