public class FileWriterTest {
public static void main (String argc[])
{
FileReader fr = null;
char read[] = new char[3];
try {
fr = new FileReader("hello.txt"); //hello.txt 内容为: “hello FileWriter”
int m;
while ( (m = fr.read(read)) !=-1 ) //利用read方法“读取的字符数,如果已到达流的末尾,则返回 -1”的特性,可以控制适当的时间来种植循环,但是最后一次未必都是读去全部的流,比如最后仅读入一个字符,而字符串宽度可能为3,这时候把全部字符串打印就会出现多出2个字符的错误,所以在new String中加以控制
{
System.out.print( new String(read,0,m ) ); //这里New String 的参数是必要的否则,就会像如上所说的,多打印字符,m反映了读取文件流中字符个数 。String(char[]value, int offset, int count)
// System.out.print("m= " + m + "," + "read= " + new String( read)+ "\n");
}
} catch (FileNotFoundException e) {
System.out.println("file not found");
} catch (IOException e) {
e.printStackTrace();
}
finally
{
if (fr != null) //这里判断文件是否打开,对于程序健壮性是有益的
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}