黑马程序员——Java基础——IO流(文本文件读取方式)

来源:互联网 发布:清华大学软件学院地址 编辑:程序博客网 时间:2024/05/19 00:54

------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

import java.io.FileReader;import java.io.IOException;/** * 读取文件 *第一种方式:通过read()方法读取 */public class FileReaderDemo {public static void main(String[] args) throws IOException{//1.创建FileReader文件读取流对象,和指定名称的文件相关联//要保证该文件是已经存在的,如果不存在,会发生FileNotFoundException异常FileReader fr = new FileReader("demo.txt");/*  2.调用read()方法读取:一次只读取一个字符。  返回:作为整数读取的字符,范围在 0 到 65535 之间 (0x00-0xffff),如果已到达流的末尾,则返回 -1int ch1 = fr.read(); System.out.println((char)ch1);int ch2 = fr.read(); System.out.println((char)ch2);int ch3 = fr.read(); System.out.println(ch3); *///3.用循环读取所有字符int ch = 0;/**while((ch=fr.read())!=-1){System.out.print((char)ch);} */while(true){ch = fr.read();if(ch == -1){break;}System.out.println((char)ch);}//3.调用close()方法关闭读取文件流fr.close();}}


/** * 读取文件 * 第二种方式:read(char[] cbuf);通过字符数组进行读取 */public class FileReaderDemo02 {public static void main(String[] args) throws IOException{//1.创建读取流FileReader对象,指定文件进行关联关联FileReader fr = new FileReader("demo.txt");int num = 0;//2.定义缓冲区数组char[] buf = new char[1024];while((num = fr.read(buf)) != -1){/* * 3.打印输出new String(char[] buf,int off,int len) *  参数buf:缓冲区目标 ; off:冲缓冲区哪个位置开始读取; len:要读取的字符数 * 不要使用System.out.println();方法打印数据,要不然就会打印一次就换一行,导致与文件本来格式不一致 */System.out.print(new String(buf,0,num));}//4.调用close()方法关闭文件流fr.close();}}



0 0
原创粉丝点击