Java,IO之FileInputStream和FileReader读取文件(疯狂java讲义)

来源:互联网 发布:虚拟物理实验室软件 编辑:程序博客网 时间:2024/05/22 13:34
import java.io.*;      public class FileInputStreamTest      {          public static void main(String[] args) throws IOException          {              //创建字节输入流              FileInputStream fis = new FileInputStream("FileInputStreamTest.java");              //创建一个长度为1024的竹筒              byte[] bbuf = new byte[1024];              //用于保存实际读取的字节数              int hasRead = 0;              //使用循环来重复“取水”的过程              while((hasRead = fis.read(bbuf))>0)              {                  //取出"竹筒"中(字节),将字节数组转成字符串输入                  System.out.println(new String(bbuf,0,hasRead));              }              fis.close();          }      }  

import java.io.*;      public class FileReaderTest      {          public static void main(String[] args) throws IOException           {              FileReader fr = null;              try              {                  //创建字符输入流                  fr = new FileReader("FileReaderTest.java");                  //创建一个长度为32的"竹筒"                  char[] cbuf = new char[32];                  //用于保存实际读取的字符数                  int hasRead = 0;                  //使用循环来重复“取水”的过程                  while((hasRead = fr.read(cbuf))>0)                  {                      //取出"竹筒"中(字节),将字节数组转成字符串输入                      System.out.println(new String(cbuf,0,hasRead));                  }              }              catch (IOException ioe)              {                  ioe.printStackTrace();              }              finally              {                  //关闭文件输入流                  if(fr != null)                  {                      fr.close();                  }              }          }      }    


原创粉丝点击