java中io的带参数的read方法-读取的字符个数

read返回的是已读取到buf数组里字符的个数;
下面代码就是将字符读取到定义的buf数组中,数组满了则返回len并进行判断

public class FileReaderTest {
	public static void main(String[] args) {
		File file = new File("D:/test.txt");
		File file2 = new File("D:/test2.txt");
		FileReader fr =null;
		FileWriter fw=null;
		//数组随便定义多大,只会影响到while的循环次数
		char[] buf=new char[32];
		int len=0;
		try {
			 fr = new FileReader(file);
			 fw=new FileWriter(file2);
			/* int i = fr.read(buf);
			 System.out.println(i);
			 System.out.println(buf);*/
			 while((len=fr.read(buf))>0){//将字符读取到数组中,数组满了进行判断>0,执行循环体,否则结束
				 System.out.println(buf);
				 fw.write(buf,0,len);//这里有两种方式,防止最后一段会出现重复的问题。即数组中有上次读取的字符
//				 buf=new char[32];
			 }
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

还有一种无参数的read方法,这时read返回的是字符对应的整数,如果已到达流的末尾,则返回 -1。

public class ReadFile {
         	public static void main(String[] args) {
		File file = new File("D:/test.txt");
		File file2 = new File("D:/test2.txt");
		FileReader fr = null;
		FileWriter fw = null;
		try {
			fr = new FileReader(file);
			fw = new FileWriter(file2);
			Character data = null;
			int n = 0;
			// 依次读取后续的数据
			while ((n = fr.read()) != -1) {
				data = (char) n;
				System.out.println(data);
				fw.write(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fr.close();
				fw.close();
			} catch (Exception e) {
			}
		}
	}
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值