- public class FileReader02_ {
- public static void main(String[] args) {
-
- }
- @Test
- public void m1() {
-
- String filePath = "e:\\hello.txt";
- FileReader fileReader = null;
- int date=0;
- try {
- fileReader = new FileReader(filePath);
- //循环读取 使用read
- while ((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) {
-
- }
- @Test
- public void m2() {
-
- String filePath = "e:\\hello.txt";
- FileReader fileReader = null;
- int readLen = 0;
- char[] buf = new char[8];
- try {
- fileReader = new FileReader(filePath);
- //循环读取 使用read
- while ((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
https://mp.csdn.net/mp_blog/creation/editor/134066255