目录
read(char[] cbuf, int start, int len)方法
1. 字节流介绍
Reader和Write类可用来处理字符串的读取和写入的操作,但Reader和Writer均是抽象类,所以并不能直接使用这两个类,而需要使用它们的子类来创建对象,再利用对象来处理读写操作。
2. Reader类常用方法
常用方法 | 功能说明 |
public int read() | 从输入流读一个字符;Returns: The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached |
public int read(char[] cbuf) | 从输入流读最多cbuf.length个字符并存入缓冲字符数组cbuf中; Returns: The number of characters read, or -1 if the end of the stream has been reached |
public int read(char[] cbuf, int start, int len) | ~最多len个字符,从字符数组的off位置开始存入 |
public long skip(long n) | ~最多向后挑n个字符 |
public boolean ready() | 判断是否做好读的准备 |
public boolean markSupported() | 测试输入流是否支持mark |
public void mark(int readAheadLimit) | 标记输入流当前位置 |
public void reset() | 重定位输入流 |
public void close() | 关闭输入流 |
3. FileReader类
在使用FileReader类读取文件时,必须先调用FileReader()构造方法创建FileReader类的对象,再利用它来调用read()方法
- FileReader类的构造方法:public FileReader(String name)—根据文件名称创建一个可读取的输入流对象
- 注意:Java把每个汉字和英文字母均作为一个字符对待,但把Enter键生成的回车换行符“\r\n”作为两个字符
4. 实例代码
read()方法
/*
使用FileReader的read方法读取文件内容
*/
import java.io.FileReader;
import java.io.IOException;
public class $1_FileRead {
public static void main(String[] args) throws IOException {
//使用FileReader类读取文件,使用read()依次读取字符,如果到达文件末返回-1
FileReader fr = new FileReader("utf.txt");
int data;
while((data=fr.read())!=-1){
System.out.print((char)data);
}
fr.close(); //垃圾回收不会处理,需要手动关闭;为保证关闭,可在if判断后用try... catch语句包围
}
}
read(char[] cbuf, int start, int len)方法
/*
使用FileReader类的read(cbuf)缓冲读取文件内容
*/
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class $2_FileRead {
public static void main(String[] args) throws IOException {
File file=new File("test.txt");
FileReader fr=new FileReader(file);
char[] cbuf=new char[5];
int len;
while((len=fr.read(cbuf))!=-1){
for (int i = 0; i < len; i++) { //缓冲读取,注意此处使用len而不能使用cbuf.length,否则会有多余的输出
System.out.print(cbuf[i]);
}
}
/*方法二:
while((len=fr.read(cbuf))!=-1){
String str=new String(cbuf,0,len);
System.out.print(str);
}
}
*/
fr.close();
}
}