import java.io.*;
class FileReaderDemo
{
public static void main(String[] args) throws IOException
{
//創建一個文件讀取流對象,和指定名稱的文件相關聯。
//要保證該文件是已經存在的,如果不存在,會發生異常
FileNotFoundException
FileReader fr = new FileReader("demo.txt");
//調用讀取流對象的read方法。
//read():一次讀一個字符。而且會自動往下讀。
int ch = 0;
while((ch=fr.read())!=-1)
{
System.out.println((char)ch);
}
/*
while(true)
{
int ch = fr.read();
if(ch==-1)
break;
System.out.println("ch="+(char)ch);
}
*/
fr.close();
}
}
第二種方式:通過字符數組進行讀取。
import java.io.*;
class FileReaderDemo2
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("demo.txt");
//定義一個字符數組。用于存儲讀到字符。
//該read(char[])返回的是讀到字符個數。
char[] buf = new char[1024];
int num = 0;
while((num=fr.read(buf))!=-1)
{
System.out.println(new String(buf,0,num));
}
fr.close();
}
} ————摘自《畢向東25天》