java 读取文本文件 注意

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();
				}
				
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值