java io流读写_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();

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值