Reader类的第二种读取方式:
通过字符数组进行读取:(此方法类属于Reader类中)int read(char[] cbuf) 将字符读入数组。
参数:
cbuf - 目标缓冲区
返回:
读取的字符数,如果已到达流的末尾,则返回 -1
用到String的方法 ,截取部分的字符串进行打印
static String valueOf(char[] data, intoffset, int count)
其中,offset是从什么位置开始,count是去几个字符
返回 char 数组参数的特定子数组的字符串表示形式
问题:
若文件很大,有上万字符,循环n多次,缓冲区的buf应该定义多大呢?
通常情况下,缓冲区会定义为1024的整数倍 ,1024是单位,一个字符时两字节,1024*2=2K
Reader读取方式2:
代码示例:
package com.itheima.day18;
import java.io.*;
public class FileReaderDemo02 {
public static void main(String[] args) throws IOException {
//创建对象
FileReader fr = new FileReader("E:\\MyEclipse 2014GA\\MyEclipse-Workspace\\VideoStudy\\src\\com\\itheima\\day18\\FileReaderTestDemo02.txt");
//用循环表示:
int num = 0;
while(( num = fr.read(buf))!=-1){
//调用String的 valueOf(char[] data, int offset, int count)方法
System.out.println(newString(buf,0,num));}
}
IOException处理
IO异常是IO流中最常见的异常,需要声明,处理! 处理流异常不能抛,具体处理要进行try-catch
3.异常分析:
若要添加流文件的指定目录不存在就会发生以下的两个异常
代码: FileWriter fw = new FileWriter("k:\\IOException.txt");\\没有此目录会报异常,
抛出异常: Catch:java.io.FileNotFoundException: k:\IOException.txt (系统找不到指定的路径),
Exception in thread "main" java.lang.NullPointerException
事实:
FileNotFoundException,此为文件找不到异常是IOException异常的一个子类 ,此时对象没有创建成功,fw = null
fw为空不能使用fw.close();这就是发生第二个空指针错误异常(java.lang.NullPointerException)的原因
为了提高代码的健壮性,尽量不免,应该怎么做呢?
解决方法:即在close之前要进行判断
if(fw != null)
fw.close();
所以finally中一定要写关于变量fw不等于null的判断
代码示例:
package com.itheima.day18;
import java.io.*;
public class FileWriterIOExceptionDemo {
public static void main(String[] args) {
//fw变量要在外要建立引用,在try中要进行初始化
FileWriter fw = null;
try {
fw = new FileWriter("E:\\MyEclipse 2014GA\\MyEclipse-Workspace\\VideoStudy\\src\\com\\itheima\\day18\\IOException.txt");
fw.write("IOException异常处理测试");
} catch (IOException e) {
System.out.println("Catch:"+e.toString());
}
finally{
try {
//关闭流资源也存在问题,所以也要对其进行try处理
if(fw != null)
fw.close();
}catch (IOException e) {
throw new Runnable("关闭流出现了异常!")
}
}
}
}