import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**文件读取方式一,read();每次读取一个字符
*
* */
public class FileReaderDemo
{
public static void main(String[] args)
{
FileReader fr=null;
try
{
//创建一个指定目录的文件读取流对象,和指定的文件相关联
//要保证该文件已经存在,如果不存在会发生异常FileNotFoundException
fr=new FileReader("Demo.txt");
//每次读取一个字符,而且会自动往下读
//读到的是该字符对应的int数值,如果读到末尾返回-1
// fr.read();
int ch=0;
while ((ch=fr.read())!=-1)
{
System.out.print((char)ch);
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(fr!=null){
try
{
fr.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
文件读取方式二
import java.io.FileReader;
import java.io.IOException;
public class FileReaderDemo2
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader("Demo.txt");
char[]buf=new char[1024];//通常定义为1024的整数倍
//把读到的字符存到buf中,返回的是读了几次
//数组长度是多少就读几次,如果读到末位则剩余几个字符读几次
//如果没有字符则返回-1
// int num1=fr.read(buf);
// System.out.print(num1);
// System.out.println("文件读取成功1:"+new String(buf,0,num1));
//
// int num2=fr.read(buf);
// System.out.print(num2);
// System.out.println("文件读取成功2:"+new String(buf,0,num2));
//
// int num3=fr.read(buf);
// System.out.print(num3);
// System.out.println("文件读取成功3:"+new String(buf,0,num3));
int num=0;
while ((num=fr.read(buf))!=-1)
{
System.out.println(new String(buf,0,num));
}
}
}