黑马程序员技术交流社区

标题: 读取文本文件的两种方法 [打印本页]

作者: mishisanyi    时间: 2015-6-12 17:28
标题: 读取文本文件的两种方法
  1. /**
  2. *
  3. */
  4. package io;

  5. import java.io.FileReader;

  6. /**
  7. * @author mshi
  8. *
  9. */
  10. public class FileReaderDemo {

  11.         /**
  12.          * @param args
  13.          */
  14.         public static void main(String[] args) {
  15.                 // TODO 自动生成的方法存根
  16.                 //使用read()读取单个字符流的方式读取文件
  17.                 /*FileReader fileReader = null;
  18.                 try {
  19.                         fileReader = new FileReader("D:\\HaxLogs1.txt");
  20.                         int i;
  21.                         char ch;
  22.                         while((i = fileReader.read())!= -1)
  23.                         {        ch = (char)i;
  24.                                 System.out.print(ch);}
  25.                 } catch (Exception e) {
  26.                         // TODO: handle exception
  27.                 }finally{
  28.                         try {
  29.                                 if(fileReader!=null)
  30.                                         fileReader.close();
  31.                         } catch (Exception e2) {
  32.                                 // TODO: handle exception
  33.                         }*/
  34.                 //使用read(char[])读取字符流并存入字符数组的方式读取文件
  35.                 FileReader fileReader = null;
  36.                 try {
  37.                         fileReader = new FileReader("D:\\HaxLogs1.txt");
  38.                         int len;
  39.                         char[] ch = new char[1024];
  40.                         while((len= fileReader.read(ch))!= -1)
  41.                         {        System.out.print(new String(ch, 0, len));
  42.                         ch =null;}
  43.                 } catch (Exception e) {
  44.                         // TODO: handle exception
  45.                 }finally{
  46.                         try {
  47.                                 if(fileReader!=null)
  48.                                         fileReader.close();
  49.                         } catch (Exception e2) {
  50.                                 // TODO: handle exception
  51.                         }
  52.                 }
  53.         }
  54. }
复制代码

代码如上,请大家验证一下




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2