使用字节流读取文件中的数据的几种方式

编程入门 行业动态 更新时间:2024-10-18 23:25:47

使用字节流读取文件中的数据的<a href=https://www.elefans.com/category/jswz/34/1769370.html style=几种方式"/>

使用字节流读取文件中的数据的几种方式

public class FileReader02_ {public static void main(String[] args) {}@Testpublic void m1() {String filePath = "e:\\hello.txt";FileReader fileReader = null;int date=0;try {fileReader = new FileReader(filePath);//循环读取 使用readwhile ((date=fileReader.read())!=-1){System.out.print((char) date);}} catch (IOException e) {e.printStackTrace();} finally {try {if (fileReader != null) {fileReader.close();}} catch (IOException e) {e.printStackTrace();}}}
}

 该方式读取速度较慢,看下一种方式:

public class FileReader02_ {public static void main(String[] args) {}@Testpublic void m2() {String filePath = "e:\\hello.txt";FileReader fileReader = null;int readLen = 0;char[] buf = new char[8];try {fileReader = new FileReader(filePath);//循环读取 使用readwhile ((readLen=fileReader.read(buf))!=-1){System.out.print(new String(buf,0,readLen));}} catch (IOException e) {e.printStackTrace();} finally {try {if (fileReader != null) {fileReader.close();}} catch (IOException e) {e.printStackTrace();}}}
}

首先定义了一个文件路径 filePath ,然后创建了一个FileReader对象fileReader来打开该文件。接下来,使用循环读取文件内容,每次读取最多8个字符,并将读取到的内容存储在缓冲区数组buf中。当读取到文件末尾时,fileReader.read(buf)返回-1,循环结束。最后,在finally块中关闭文件流。如果在打开文件或读取文件过程中发生异常,会捕获并打印异常信息。

输出乱码?传送门:CSDN

更多推荐

使用字节流读取文件中的数据的几种方式

本文发布于:2023-12-03 07:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1652654.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:几种   字节   方式   文件   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!