编程语言
首页 > 编程语言> > Java readLine()、read()、read(char cbuf[])、read(char cbuf[], int off, int len)详解

Java readLine()、read()、read(char cbuf[])、read(char cbuf[], int off, int len)详解

作者:互联网

BufferReader继承Reader,主要有readLine()、read()、read(char cbuf[])、read(char cbuf[], int off, int len)方法,下面我来讲解这几个方法的用法和注意事项。

先在D盘下建立一个test.txt文件(Windows系统),文件内容:

Hello
Android
2020-01-15

readLine()

该方法就是用来读取一行字符流数据,用法如下:

package s1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class X {
	public static void main(String[] args) {
		File file = new File("D:\\test.txt");
		FileReader fileReader;
		BufferedReader bufferedReader = null;
		try {
			fileReader = new FileReader(file);
			bufferedReader = new BufferedReader(fileReader);
			StringBuilder stringBuilder = new StringBuilder();
			String s;
			while ((s = bufferedReader.readLine()) != null) {
				stringBuilder.append(s);
				stringBuilder.append("\n");
			}
			System.out.println(stringBuilder.toString());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

运行结果如下:

Hello
Android
2020-01-15

read()

该方法每次只读取一个字符,用法和readLine()差不多,就不多写了。

read(char cbuf[])

该方法是每次读取cbuf.length个字符到cbuf数组里面,源码里面该方法其实调用的是read(char cbuf[], int off, int len)。即read(cbuf, 0, cbuf.length)

read(char cbuf[], int off, int len)

该方法正确的含义是:读取len个字符,然后从cbuf[off]开始存放,因此必须注意len+off不能大于cbuf.length,否则会报数组越界异常。常见的错误理解是:BufferReader跳过off个字符,然后读取len个字符到cubf数组里。

package s1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class X {
	public static void main(String[] args) {
		File file = new File("D:\\test.txt");
		FileReader fileReader;
		BufferedReader bufferedReader = null;
		try {
			fileReader = new FileReader(file);
			bufferedReader = new BufferedReader(fileReader);
			char[] cbuf = new char[4];
			bufferedReader.read(cbuf, 2, cbuf.length - 2);
			System.out.println(Arrays.toString(cbuf));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

运行结果:

[ , , H, e]

 

 

陈贵贵 发布了74 篇原创文章 · 获赞 4 · 访问量 1万+ 私信 关注

标签:java,read,char,int,bufferedReader,io,import,cbuf
来源: https://blog.csdn.net/GracefulGuigui/article/details/103993968