黑马程序员技术交流社区
标题:
关于IO流(文本文件读取方式的问题)
[打印本页]
作者:
蓝枫
时间:
2014-3-29 10:36
标题:
关于IO流(文本文件读取方式的问题)
import java.io.*;
class FileReaderDemo
{
public static void main(String[] args)throws Exception
{
FileReader fr = new FileReader("demo.txt");
//定义一个字符数组,用于存储读到的字符
//该read(char[])返回的是读到字符个数
char[] buf = new char[1024];//这个字符数组的长度为什么要定义成1024呢?
int num = 0;
while((num=fr.read(buf))!=-1)
{
System.out.println(new String(buf,0,num));//这个输出语句不是很明白?
//new String(buf,0,num)怎么理解这句代码?
}
fr.close();
}
}
复制代码
作者:
也许依然
时间:
2014-3-29 13:39
class FileReadDemo
{
public static void main(String[] args) throws Exception
{
//定义一个文件读取流对象
FileReader fr = new FileReader("demo.txt");
//定义一个字符数组,用作缓冲区,存储读到的字符
char [] buf = new char[1024]; //缓冲区的大小是任意的,将数组的大小定义为1024是最优化的选择,也可以是1024*2,1024*4等
///定义一个int型的数据,用于记录每次循环从缓冲区中读到的字符数
int len = 0;
while((len = fr.read(buf))!=-1)
{
/*String(buf,0,len) 为字符串的构造函数
String(char[] value, int offset, int count)
指分配一个新的字符串,将buf字符数组的0位置开始,长度为len的字符复制到新字符串中*/
//new String(buf,o,len);为创建一个字符串对象
System.out.println(new String(buf,0,len)); //将字符串的内容打印
}
fr.close();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2