如何用FileReader,BufferedReader,FileInputStream读取文档



package test5;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;


public class TestFile3 {
 public static void main(String[] args)  {
 System.out.println("使用FileReader方法读取:"); 
 FileReader f1 = null;
  try {
   f1 = new FileReader("E:/HelloWorld.java");
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  int i;
  try {
   while((i=f1.read())!=-1){
    System.out.print((char)(i));
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   f1.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("\n");
  System.out.println("使用BufferedReader方法读取:");
  FileReader h = null;
  try {
   h = new FileReader("e:/HelloWorld.java");
  } catch (FileNotFoundException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  BufferedReader f2=null;
  try{
   f2=new BufferedReader(h);
   String j=" ";
   while((j=f2.readLine())!=null){
    System.out.println(j);
   }
  }catch(IOException e){
   e.printStackTrace();
  }
  finally{
   if(f2!=null){
    try{
     f2.close();
    }catch(IOException e){
     e.printStackTrace();
    }
   }
  }
 
  System.out.println("\n");
  
  System.out.println("使用FileInputStream方法读取:");
  
  File f=new File("E:/HelloWorld.java");
  FileInputStream f3 = null;
  try {
   f3 = new FileInputStream(f);
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  byte b[]=new byte[1024];
  int len=0;
  int temp=0;
  try {
   while((temp=f3.read())!=-1){
    b[len]=(byte)temp;
    len++;
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   f3.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(new String(b,0,len));
  
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值