读取文本内容方式:
1. 字节流方式, 使用FileInputStream类
2. 字符流方式, 使用FileReader类
如果如本文所示, 仅仅只是读取文本内容的话, 几乎都是用的字符流方式.
相对于字节流方式来说,字符流方式会更加方便.
扩展内容: 但是, 这也不是说FileInputStream没有它的价值.
我们经常涉及的都是从文件中读取数据,以字符的形式显示出来.
不过有些文件则必须用FileInputStream读取, 例如: 图像文件, 流媒体文件等.
这个时候,就得使用字符流方式读取文件内容.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @TODO 读取文本内容
* @author jarg
* @creatTime: 2010-12-29 下午08:00:40
* @belongTo: com.jarg.io
* @version 1.0
*/
public class FileInput
{
public static void main(String[] args) throws IOException
{
/**
* 字节流方式
* */
FileInputStream fi = new FileInputStream("temp.txt");
InputStreamReader ir = new InputStreamReader(fi);
BufferedReader br = new BufferedReader(ir);
display(br);
/**
* 字符流方式
* */
FileReader fr = new FileReader("temp.txt");
BufferedReader br2 = new BufferedReader(fr);
display(br2);
}
/**
* @throws IOException
* @TODO 输出文本内容
*/
public static void display(BufferedReader br) throws IOException
{
String output;
while((output = br.readLine()) != null)
{
System.out.println(output);
}
}
}