Java IO流文件的读取操作方式

/************************************************************************************
* 需求:以文件流的形式读取指定桌面的test_iosstream.txt文件并输出到控制台显示出内容
* 实现思路:将指定字符串路径filename转化为文件对象;方式一以字节流对象操作文件,每次读取一个字节并输出到控制台直至读取完;方式二以字符流对象操作文件,每次读取一个字符并输出到控制台,直至读取完;方式三以默认缓冲流的方式读取文件内容,每次读取一行数据,直至读取完;最后三种方式都得关流操作!
* 知识要点:方式一和二读取到文件的末尾再读取无内容时读取的流长度为-1,方式三读取到文件结尾再读取无内容则返回为null;不论那种方式读取流操作都可能出现IO流异常故必须try and catch并finally最终关闭流操作;
***********************************************************************************/
import java.io.*;
import java.nio.charset.Charset;
public class Test_IOStream{

public static void main(String[] args){
String filename = "C:\\Users\\Administrator\\Desktop\\test_iostream.txt";
// readFileByByte(filename);
// readFileByChar(filename);
readFileByBuffer(filename);
}

/*
* 方式一:读取文件系统字节流方式读取文件
*/
public static void readFileByByte(String filename){
File readFile = new File(filename); //根据路径名构造文件对象
InputStream in = null; //定义字节流
try{
in = new FileInputStream(readFile); //实例化字节流对象
int readbyte;
while((readbyte=in.read())!=-1){ //每次读取一个字节(0-255)
System.out.write(readbyte); //输出出去
}
in.close();
}catch(Exception e){
e.printStackTrace();
}finally{
if(in!=null){
try{
in.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}

/*
* 方式二: 读取文件系统字符流方式读取文件
*/
public static void readFileByChar(String filename){
File readFile = new File(filename);
Reader rd = null;
try{
rd = new InputStreamReader(new FileInputStream(readFile),Charset.forName("UTF-8"));
int tempchar;
while((tempchar=rd.read())!=-1){
if((char)tempchar!='\r'){
System.out.write(tempchar);
}
}
rd.close();
}catch(IOException e){
e.printStackTrace();
}finally{
if(rd!=null){
try{
rd.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

}

/*
* 方式三: 读取文件系统缓冲字符流方式读取文件
*/
public static void readFileByBuffer(String filename){
// File readFile = new File(filename);
BufferedReader br = null;
try{
// br = new BufferedReader(new FileReader(readFile));
br = new BufferedReader(new FileReader(filename));
String rline = null;
while((rline=br.readLine())!=null){
System.out.println(rline);
}
br.close();
}catch(IOException e){
e.printStackTrace();
}finally{
if(br!=null){
try{
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
posted @ 2018-08-02 16:42  fgh1101  阅读(6396)  评论(0编辑  收藏  举报