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

  • 相关阅读:
    vue学习记录(四)---router的运用
    node.js 框架express关于报错页面的配置
    node.js 的热更新
    yii2 Menu组件的使用
    node.js 框架express有关于router的运用
    node.js 的页面渲染方法ejs
    什么是mybatis
    如何清除maven中下载失败的包
    hibernate 执行步骤
    什么是ORM
  • 原文地址:https://www.cnblogs.com/guanghe/p/9443777.html
Copyright © 2011-2022 走看看