Java读取文件

复制代码
 1 public static String getFileStr(String filePath) {
 2     InputStream is = null;
 3     BufferedInputStream bis = null;
 4     ByteArrayOutputStream bos = null;
 5     byte[] buffer = new byte[1024];
 6     int length = 0;
 7     try {
 8         is = FileUtil.class.getClassLoader().getResourceAsStream(filePath);
 9         bis = new BufferedInputStream(is);
10         bos = new ByteArrayOutputStream();
11         while((length = bis.read(buffer)) != -1) {
12             bos.write(buffer, 0, length);
13         }
14         bos.flush();
15         String str = bos.toString("UTF-8"); 
16         return str;
17     } catch (Exception e) {
18         e.printStackTrace();
19     } finally {
20         try {                
21             if(bos != null) {
22                 bos.close();
23             }
24             if(bis != null) {
25                 bis.close();
26             }
27             if(is != null) {
28                 is.close();
29             }
30         } catch (Exception e) {
31             e.printStackTrace();
32         }
33     }
34     return null;
35 }
复制代码

注意:

  一定要使用具体文件的类获取文件流:FileUtil.class.getClassLoader().getResourceAsStream(filePath),有/代表用绝对路径,没有使用相对。

  千万不要用:ClassLoader.getSystemResourceAsStream(filePath), 无论加不加/、各种拼路径都读不到文件!!!因为这个浪费了我大量时间!!!

posted @   光何  阅读(562)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~

点击右上角即可分享
微信分享提示