BufferedReader
准备工作
准备一个news.txt文件,内容如下,字符编码为UTF8
常用构造器
-
public BufferedReader(Reader in)
传入一个Reader或者Reader子类对象,创建使用默认大小8192的输入缓冲区的缓冲字符输入流
-
public BufferedReader(Reader in, int sz)
传入一个Reader或者Reader子类对象,创建使用指定大小的输入缓冲区的缓冲字符输入流
1 2
| BufferedReader bufferedReader = new BufferedReader(new FileReader("E://news.txt"));
|
1 2
| BufferedReader bufferedReader = new BufferedReader(new FileReader("E://news.txt"), 8192);
|
close
关闭BufferedReader流对象,值得一提的是,这里关闭外部流对象BufferedReader即可,内部流会自动关闭
public void close() throws IOException
1 2
| BufferedReader bufferedReader = new BufferedReader(new FileReader("E://news.txt")); bufferedReader.close();
|
ready、read 、skip
请参考:FileReader和FileWriter类方法详解
readline
一次从文件中读取一行,返回读取到的字符串,达到文件末尾时返回null
public String readLine() throws IOException
1 2 3 4 5 6 7 8 9 10 11
| BufferedReader bufferedReader = new BufferedReader(new FileReader("E://news.txt")); String data = null; while ((data = bufferedReader.readLine()) != null) { System.out.println(data); } bufferedReader.close();
|
markSupported
查看BufferedReader是否支持markSupported,答案是肯定的,BufferedReader支持reset和mark
public boolean markSupported()
1 2 3 4
| BufferedReader bufferedReader = new BufferedReader(new FileReader("E://news.txt")); System.out.println(bufferedReader.markSupported());
|
mark
给文件指定位置mark一下,做个标记,在读取readAheadLimit个字节之后mark失效
public void mark(int readAheadLimit) throws IOException
1 2 3
| BufferedReader bufferedReader = new BufferedReader(new FileReader("E://news.txt")); bufferedReader.mark(10); bufferedReader.close();
|
reset
可以将文件从重置到mark位置
``
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| BufferedReader bufferedReader = new BufferedReader(new FileReader("E://news.txt"));
bufferedReader.mark(50); String data = null; while ((data = bufferedReader.readLine()) != null) { System.out.println(data); }
bufferedReader.reset(); while ((data = bufferedReader.readLine()) != null) { System.out.println(data); } bufferedReader.close();
|
BufferedWriter
准备工作
准备一个news.txt文件,内容如下,字符编码为UTF8
常用构造器
-
public BufferedWriter(Writer out)
传入一个Writer或者Writer子类对象,创建使用默认大小的输出缓冲区的缓冲字符输出流
-
public BufferedWriter(Writer out, int sz)
传入一个Writer或者Writer子类对象,创建使用指定大小的输出缓冲区的缓冲字符输出流
writer、close、flush
见FileReader和FileWriter类方法详解
close:关闭BufferedWriter流对象,值得一提的是,这里关闭外部流对象BufferedWriter即可,内部流会自动关闭
newline
在文件中输入换行符,等价于插入\n
public void newLine() throws IOException
1 2 3 4 5 6 7 8 9 10
| BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("E:\\news.txt")); bufferedWriter.write("床前明月光,"); bufferedWriter.newLine(); bufferedWriter.write("疑是地上霜。"); bufferedWriter.newLine(); bufferedWriter.write("举头望明月,"); bufferedWriter.newLine(); bufferedWriter.write("低头思故乡。"); bufferedWriter.flush(); bufferedWriter.close();
|
结果