黑马程序员—IO流FileReader

来源:互联网 发布:淘宝平面设计 编辑:程序博客网 时间:2024/05/20 15:59
//第1种方式:一次读一个字符,并打印一次class FileReaderDemo{public static void main(String[] args)throws IOException{/*创建一个文件读取流对象,和指定名称的文件相关联 *要保证该文件是已经存在的,如果不存在,会发生异常FileNotFoundException */FileReader fr=new FileReader("demo2.txt");/*调用读取流对象的read方法 *read():一次读一个字符,而且会自动往下读,将读取的字符会作为整数返回 */int ch1=fr.read();System.out.println("ch1="+(char)ch1);//加上char是强转成字符型,不加char打印的是int型int ch2=fr.read();System.out.println("ch2="+(char)ch2);int ch3=fr.read();System.out.println("ch3="+(char)ch3);int ch4=fr.read();System.out.println("ch4="+(char)ch4);int ch5=fr.read();System.out.println("ch5="+(char)ch5);//文件里只有4个字符,第5个不存在,所以ch5=-1fr.close();}}/* * 运行结果为: * ch1=a * ch2=b * ch3=c * ch4=d * ch5=-1//用read方法读取文件中的字符,当已经读到文件末尾的时候,返回-1 *  * close在写的时候要先刷新再关闭资源,而在读的时候只关闭资源不用刷新 *///上面这个读取文件的写法不对,因为不知道文件中有多少字符,所以不知道该读多少次,因此应该用循环的写法class FileReaderDemo1{public static void main(String[] args)throws IOException{FileReader fr=new FileReader("demo4.txt");while(true){int ch=fr.read();if(ch==-1)break;System.out.println("ch="+(char)ch);}fr.close();}}/* * 运行结果为: * ch=a * ch=b * ch=c * ch=d * ch=e * ch=1 *///以上代码修整一下,最终写为:class FileReaderDemo2{public static void main(String[] args)throws IOException{FileReader fr=new FileReader("demo4.txt");int ch=0;while((ch=fr.read())!=-1){System.out.println("ch="+(char)ch);}fr.close();}}/* * 运行结果为: * ch=a * ch=b * ch=c * ch=d * ch=e * ch=1 *///第2种方式:通过字符数组进行存储,再一次全部读完class FileReaderDemo3{public static void main(String[] args)throws IOException{FileReader fr=new FileReader("demo4.txt");/* 定义一个字符数组,用于存储读到的字符 * 该read(char[])返回的是读到的字符个数 */char[] ch=new char[3];//定义了一个长度为3的字符数组int num=fr.read(ch);//把流中的数据读3个存到数组里面去,返回的是存的个数System.out.println("num="+num+"::"+new String(ch));//也可用Arrays.toString(ch);将字符数组转成字符串int num1=fr.read(ch);System.out.println("num1="+num1+"::"+new String(ch));int num2=fr.read(ch);System.out.println("num2="+num2+"::"+new String(ch));fr.close();}}/* * 运行结果为: * num=3::abc * num1=3::de1 * num2=-1::de1//再读没有数据了,所以返回-1 *///但以上方法不知道要读到什么时候为止,所以可以写为:class FileReaderDemo4{public static void main(String[] args)throws IOException{FileReader fr=new FileReader("demo4.txt");char[] ch=new char[1024];//怕数据较多数组装不下,所以数据长度定义为1024,如果要装的数据更大就可以装                         //1024的整数倍int num=0;while((num=fr.read(ch))!=-1){System.out.println(new String(ch,0,num));//(ch,0,num)表示读到几个打印几个}fr.close();}}/* * 运行结果为: * abcde1 *///和两种度的方式哪种较好呢?第二种较好,因为第二种一次读完再一次打印

0 0
原创粉丝点击