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), 无论加不加/、各种拼路径都读不到文件!!!因为这个浪费了我大量时间!!!

原文地址:https://www.cnblogs.com/guanghe/p/9443777.html