java文件读取(按字符读+按字节读+缓冲读取)FileReader FileInputStream BufferedReader


在D盘下新建一个文本文件in.txt,路径为(D:\\in.txt),在里面写入一些字符

1.按字符读取文件

package 文件读取;
/**
 * 功能:按字符读取文件
 * 时间:2011.6.1  23.33
 */
import java.io.*;
public class 按字符读取文件 {
 public static void main(String[] args){
  //File f = new File("D:\\io.txt");
  FileReader fr = null;
  try {
   fr = new FileReader("D:\\in.txt");
   int n = 0;
   char[] c = new char[1024];
   while((n=fr.read(c))!=-1){
    System.out.println(c);
    String s = new String(c,0,n);
    System.out.println(s);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   try {
    fr.close();
   } catch (Exception e2) {
    e2.printStackTrace();
   }
  }
 }
}

2.按字节读取文件

package 文件读取;
import java.io.*;
public class 按字节读取文件 {
 public static void main(String[] args){
  FileInputStream fis = null;
  try {
   File f = new File("D:\\in.txt");
   fis = new FileInputStream(f);
   byte[] b = new byte[1024];
   int n = 0;
   while((n=fis.read(b,0,1024))!=-1){
    String s = new String(b,0,n);
    System.out.println(s);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

3.缓冲读取文件

package 文件读取;
/*
 * 缓冲读取
 * */
import java.io.*;
public class 缓冲读取文件 {
 public static void main(String[] args){
  BufferedReader br = null;
  try {
   FileReader fr = new FileReader("D:\\in.txt");
   br = new BufferedReader(fr);
   String s = "";
   while((s=br.readLine())!=null){
    System.out.print(s);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  //FileReader fr = new FileReader("D:\\test.txt");
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值