20-IO流-07-IO流(字符流-FileReader-读取方式二)

package cn.itcast.ioread.demo;

import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo2 {

	public static void main(String[] args) throws IOException {
		// 使用read(char[])读取文本文件数据
		/**
		 * 方法: public int read(char[] cbuf) throws IOException
		 * 
		 * 功能:将字符读入数组。在某个输入可用、发生I/O错误或者已到达流的末尾前,此方法一直阻塞。
		 * 
		 * 返回:读取的字符数,如果已到达流的末尾,则返回-1
		 */
		FileReader fr = new FileReader("demo.txt");// 该文件内容:abcde

		char[] buf = new char[3];

		// int num = fr.read(buf);//这里可以直接将读取到的字符存入事先建立的数组中
		// System.out.println(num + ":" + new String(buf));//3:abc
		//
		// int num1 = fr.read(buf);
		// System.out.println(num1 + ":" + new
		// String(buf));//2:dec
		//
		// int num2 = fr.read(buf);
		// System.out.println(num2 + ":" + new String(buf));//-1:dec

		// 修改以上程序
		// int num = fr.read(buf);
		// //String构造函数,可以指定将数组中的某一段变成字符串
		// System.out.println(num+":"+new String(buf,0,num));//3:abc
		//
		// int num1 = fr.read(buf);
		// //因为只读取了num1个元素,也就是到num1为止,避免了dec的情况
		// System.out.println(num1+":"+new String(buf,0,num1));//2:de
		// fr.close();

		// 再次修改程序
		int len = 0;
		while ((len = fr.read(buf)) != -1) {
			System.out.print(new String(buf, 0, len));//abcde
		}
	}
	//注:char[] buf = new char[3];中数组长度一般指定为1024的整数倍

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值