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

  • 相关阅读:
    做汉堡
    作业三 读《构建之法》
    一个程序员的生命周期--有感
    阅读《构建之法》第13-17章
    阅读<构建之法>10、11、12章
    阅读《构建之法》第8,9,10章
    测试与封装5.2-5.3
    作业5 四则运算 测试与封装 5.1
    阅读5-7章
    做汉堡
  • 原文地址:https://www.cnblogs.com/guanghe/p/9443777.html
Copyright © 2011-2022 走看看