java读取txt文件内容

7 篇文章 0 订阅
/**
 * 为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally
 */
public void testFileReader(){
   FileReader fileReader = null;
   try {
       // 1. 实例化File类对象,指明要操作的对象
       File file = new File("hello.txt");
       // 2. 提供具体的流
       fileReader = new FileReader(file);
       // 3. 数据的读入过程
       // read() 返回读入的一个字符。如果达到文件末尾,返回-1
       int data;
       while(-1 != (data = fileReader.read())){
           System.out.print((char)data);
       }
   } catch (IOException e) {
       e.printStackTrace();
   } finally {
       try {
           // 4. 流的关闭
           if(fileReader != null) fileReader.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}
/**
 * 使用read()的重载方法
 */
public void testFileReader1(){
    FileReader fileReader = null;
    try {
        // 1. file 实例化
        File file = new File("hello.txt");
        // 2. FileReader流的实例化
        fileReader = new FileReader(file);
        // 3. 读入的操作
        // read(char[] cbuf) 返回每次读入cbuf数组中的字符个数。如果达到文件末尾返回-1
        char[] cbuf = new char[2];
        int len;
        while ((len = fileReader.read(cbuf)) != -1){
            // 方式一
            /*for (int i = 0; i < len; i++) {
                System.out.print(cbuf[i]);
            }*/
            // 方式二
            String str = new String(cbuf,0,len);
            System.out.print(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 4. 关闭资源
            if(fileReader != null)fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值