在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

JAVA实现读取txt文件内容的方法

2017-3-7 12:50| 发布者: zhangjf| 查看: 1070| 评论: 0

摘要: 通常,我们可以直接通过文件流来读取txt文件的内容,但有时可能会出现乱码!此时只要设置一下文件字符编码即可。 public class txttest { /** * 读取txt文件的内容 * @param file 想要读取的文件对象 * @ret ...

通常,我们可以直接通过文件流来读取txt文件的内容,但有时可能会出现乱码!此时只要设置一下文件字符编码即可。

  1. public class txttest {
  2. /**
  3. * 读取txt文件的内容
  4. * @param file 想要读取的文件对象
  5. * @return 返回文件内容
  6. */
  7. public static String txt2String(File file){
  8. StringBuilder result = new StringBuilder();
  9. try{
  10. BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
  11. String s = null;
  12. while((s = br.readLine())!=null){//使用readLine方法,一次读一行
  13. result.append(System.lineSeparator()+s);
  14. }
  15. br.close();
  16. }catch(Exception e){
  17. e.printStackTrace();
  18. }
  19. return result.toString();
  20. }
  21. public static void main(String[] args){
  22. File file = new File("D:/errlog.txt");
  23. System.out.println(txt2String(file));
  24. }
  25. }
复制代码

读取文件效果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-4 02:45

Copyright 2015-2025 djqfx

返回顶部