FileReader读取数据方法(一)

来源:互联网 发布:怎么申请淘宝 编辑:程序博客网 时间:2024/05/14 06:52
package cn.io;//FileReader读取数据方法(一)//注意://(1)FileReader的read(char [] cbuf)方法,返回的是读取的个数//   若读取对象很大,则已经读了1024时那么就将缓存数组的东西写入到copyhao.txt,使其清空然后继续复制的过程。//   最后总会出现装一次不满1024的情况//(2)关闭流的顺序:后开的先关//(3)之所以把FileReader fr = null和FileWriter fw = null;//   是因为它们是全局的,若在try里面这么写,那么在finally里就无法识别////import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class Test2 {public static void main(String[] args) {FileReader fr = null;FileWriter fw = null;try {fr = new FileReader("F:\\hao.txt");fw = new FileWriter("F:\\copyhao.txt");char[] charArr = new char[1024];int length = 0;// 往里面读取了多少.读取的字符数,如果已到达流的末尾,则返回 -1while ((length = fr.read(charArr)) != -1) {fw.write(charArr, 0, length);}} catch (IOException e) {e.toString();} finally {try {if (fw != null) {fw.close();}} catch (IOException e) {e.toString();}try {if (fr != null) {fr.close();}} catch (IOException e) {e.toString();}}}}

原创粉丝点击