温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JAVA读取文本文件内容实例代码

发布时间:2020-08-26 13:27:03 来源:脚本之家 阅读:97 作者:xing_star 栏目:编程语言

java读取文本文件内容

今天写代码写着要调试一个很长的字符串,就用idea新建了text文本,存放长字符串的内容。结果发现读取文本文件内容的java代码不怎么会写了,果然是面向百度编程,面向control c 或者control v编程,尴尬。

最终的代码如下:

public static String readFileContent(String fileName) {
  File file = new File(fileName);
  BufferedReader reader = null;
  StringBuffer sbf = new StringBuffer();
  try {
    reader = new BufferedReader(new FileReader(file));
    String tempStr;
    while ((tempStr = reader.readLine()) != null) {
      sbf.append(tempStr);
    }
    reader.close();
    return sbf.toString();
  } catch (IOException e) {
    e.printStackTrace();
  } finally {
    if (reader != null) {
      try {
        reader.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
  return sbf.toString();
}

留个小问题,这种方式只能读取普通的文本文件,对于二进制之类的文件,是不可以的,那应该如何做呢,嗯,等碰到这样场景的需求再记录下来吧。

Java一次读取文本文件所有内容

我们做文本处理的时候的最常用的就是读写文件了,尤其是读取文件,不论是什么文件,我都倾向于一次性将文本的原始内容直接读取到内存中再做处理,当然,这需要你有一台大内存的机器,内存不够者……可以一次读取少部分内容,分多次读取。

读取文件效率最快的方法就是一次全读进来,很多人用readline()之类的方法,可能需要反复访问文件,而且每次readline()都会调用编码转换,降低了速度,所以,在已知编码的情况下,按字节流方式先将文件都读入内存,再一次性编码转换是最快的方式,典型的代码如下:

public String readToString(String fileName) { 
    String encoding = "UTF-8"; 
    File file = new File(fileName); 
    Long filelength = file.length(); 
    byte[] filecontent = new byte[filelength.intValue()]; 
    try { 
      FileInputStream in = new FileInputStream(file); 
      in.read(filecontent); 
      in.close(); 
    } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
    try { 
      return new String(filecontent, encoding); 
    } catch (UnsupportedEncodingException e) { 
      System.err.println("The OS does not support " + encoding); 
      e.printStackTrace(); 
      return null; 
    } 
  }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI