java学习笔记之BufferedReader与BufferedWriter
2016-07-13 19:13
465 查看
1. 使用缘由
为了提高字符流读写的效率,引入了缓冲机制,进行字符批量的读写,提高了单个字符读写的效率。BufferedReader用于加快读取字符的速度,BufferedWriter用于加快写入的速度
2. BufferedWriter
2.1 继承体系与方法
java.lang.Object ----java.io.Writer ------java.io.BufferedWriter
构造方法
BufferedWriter(Writer out) Creates a buffered character-output stream that uses a default-sized output buffer. BufferedWriter(Writer out, int sz)//sz可以指定缓冲区的大小 Creates a new buffered character-output stream that uses an output buffer of the given size
常见方法
void close() Closes the stream, flushing it first. void flush() Flushes the stream. //刷新缓存区 void newLine() Writes a line separator. //添加换行符 void write(char[] cbuf, int off, int len) Writes a portion of an array of characters. //写入指定的字符数组,off起始偏移量,len要写入的字符长度 void write(int c) Writes a single character. void write(String s, int off, int len) Writes a portion of a String. //写入指定的字符串,off偏移量,len要 入的字符串长度
2.2实例代码
package ReaderWriter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /* * @author pecu * */ public class BufferedWriterReview { public static void main(String[] args) { //writeFile1(); writeFile2(); } private static void writeFile2() { BufferedWriter bw=null; BufferedReader br=null; try { br = new BufferedReader(new FileReader("fw.txt")); bw = new BufferedWriter(new FileWriter("bw2.txt")); String buff=null; while((buff=br.readLine())!=null){ //读取行,不包含换行符 //将读取的行内容写入文件,偏移量为0,写入长度为buff的长度 bw.write(buff, 0,buff.length()); bw.newLine(); // 添加换行 } } catch (IOException e) { e.printStackTrace(); }finally{ if(br!=null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if(bw!=null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static void writeFile1() { BufferedWriter bw=null; BufferedReader br=null; try { br = new BufferedReader(new FileReader("fw.txt")); bw = new BufferedWriter(new FileWriter("bw.txt")); char buff[] = new char[1024]; int len; while((len=br.read(buff))!=-1){ bw.write(buff, 0, len); } } catch (IOException e) { e.printStackTrace(); }finally{ if(br!=null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if(bw!=null){ try { bw.close()` } catch (IOException e) { e.printStackTrace(); } } } } }
3. BufferedReader
3.2 继承体系与方法
1、继承体系java.lang.Object ----java.io.Reader ----java.io.BufferedReader
2、构造方法
1、BufferedReader(Reader in) Creates a buffering character-input stream that uses a default-sized input buffer. 2、BufferedReader(Reader in, int sz)//sz可以指定缓冲区的大小 Creates a buffering character-input stream that uses an input buffer of the specified size.
3、常见方法
void close() Closes the stream and releases any system resources associated with it. int read() Reads a single character. //读取单个字符 int read(char[] cbuf, int off, int len) Reads characters into a portion of an array. //读取到cbuf,off开始存储的偏移量,len读取的长度 String readLine() Reads a line of text. //读取一行,不包含换行符 long skip(long n) Skips characters.//n为跳过的字符个数 boolean ready() Tells whether this stream is ready to be read. void reset() Resets the stream to the most recent mark.
3.2 实例代码
package ReaderWriter; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; * * @author pecu * */ public class BufferedReaderReview { public static void main(String[] args) { readFile(); } private static void readFile() { FileReader fr=null; BufferedReader br=null; try { fr=new FileReader("fw.txt"); br = new BufferedReader(fr); String line=null; while((line=br.readLine())!=null){//不包含 line-termination characters System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(br!=null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
4 自定义BufferedReader与BufferedWriter
自定义BufferedReader/** * * @author pecu * */ public class CustomBufferedReader extends Reader{ Reader r; private char[] buff; // 字符缓冲区 private int lineNumber=0; // 行号 public CustomBufferedReader(Reader r) { super(); this.r = r; buff = new char[8192]; } public int readInt() throws IOException{ return r.read(); } public String readLine2() throws IOException { int ch = 0; StringBuffer sb = new StringBuffer(); synchronized (lock) { while((ch=readInt()) != -1){ if(ch == '\r'){ continue; } if(ch == '\n'){ ++lineNumber; return sb.toString(); } sb.append((char)ch); } } if(sb.length()==0) return null; ++lineNumber; return sb.toString(); } public String readLine() throws IOException { int ch = 0; int count = 0; synchronized (lock) { while((ch=readInt()) != -1){ // 不到文件结尾 if(ch == '\r'){ // '\r'不存 continue; } if(ch == '\n' ){ ++lineNumber; return new String(buff,0,count); } buff[count++]= (char) ch; } } if(count==0) return null; //如果读取为空 ++lineNumber; return new String(buff,0,count); } public void close() throws IOException { if (r!=null) { r.close(); } } public int getLineNumber() { return lineNumber; } @Override public int read(char[] cbuf, int off, int len) throws IOException { checkBounds(cbuf, off, len); return r.read(cbuf, off, len); } /** * 检查边界 * * @param cbuf * @param off * @param len */ private void checkBounds(char[] cbuf, int off, int len) { if (cbuf == null) { throw new NullPointerException("cbuf is null"); } if ((off < 0 || off > cbuf.length) || (len < 0 || len > cbuf.length) || (off + len) < 0 || (off + len) > cbuf.length) { throw new ArrayIndexOutOfBoundsException(); } if (0==len) { return; } } }
自定义BufferedWriter
/** * @author pecu */ public class CustomBufferedWriter extends Writer { private static final String LINE_SEPARATOR = System .getProperty("line.separator"); private Writer writer; private static final int cacheSize = 8192; // 默认缓冲 private char buff[]; // 缓冲区 private int nChars, charIndex; // public CustomBufferedWriter(Writer writer) { this(writer, cacheSize); } public CustomBufferedWriter(Writer writer, int sz) { super(); if (sz <= 0) { throw new IllegalArgumentException("Buffered sz<=0"); } this.writer = writer; nChars = sz; charIndex = 0; buff = new char[sz]; } public void newLine() throws IOException { write(LINE_SEPARATOR); // write(LINE_SEPARATOR,0,LINE_SEPARATOR.length()); } public void write(int c) throws IOException { if (charIndex >= nChars) { flushBuffer(); } buff[charIndex++] = (char) c; } public void write(String str) throws IOException{ write(str, 0, str.length()); } @Override public void write(String str, int off, int len) throws IOException { securityCheck(); // 1 // char[] charArray = str.toCharArray(); // write(charArray, off, len); // 2 while (len>0) { int lenght=Math.min(nChars-charIndex, len); str.getChars(off, off+lenght, buff, charIndex); len-=lenght; charIndex+=lenght; if (charIndex>=nChars) { flushBuffer(); } } } @Override public void write(char[] cbuf, int off, int len) throws IOException { synchronized (lock) { checkBounds(cbuf, off, len); if (len>=nChars) { flushBuffer(); writer.write(cbuf, 0, len); return; } while (len>0) { int length=Math.min(nChars-charIndex, len); System.arraycopy(cbuf, off, buff, charIndex, length); len-=length; charIndex+=length; if (charIndex>=nChars) { flushBuffer(); } } } } /** * 检查边界 * * @param cbuf * @param off * @param len */ private void checkBounds(char[] cbuf, int off, int len) { if (cbuf == null) { throw new NullPointerException("cbuf is null"); } if ((off < 0 || off > cbuf.length) || (len < 0 || len > cbuf.length) || (off + len) < 0 || (off + len) > cbuf.length) { throw new ArrayIndexOutOfBoundsException(); } if (0==len) { return; } } @Override public void flush() throws IOException { synchronized (lock) { securityCheck(); flushBuffer(); writer.flush(); } } @Override public void close() throws IOException { synchronized (lock) { securityCheck(); flush(); writer = null; buff = null; } } /** * 刷新到字符流 * * @throws IOException */ public void flushBuffer() throws IOException { synchronized (lock) { securityCheck(); if (charIndex == 0) return; writer.write(buff, 0, charIndex); charIndex = 0; } } /** * 检查流是否关闭 * * @throws IOException */ public void securityCheck() throws IOException { if (writer == null) { throw new IOException("stream closed"); } } }
注:以上只是简单的功能实现,全面了解可参考源码。
相关文章推荐
- 踩坑笔记——JavaScript判断回文程序
- BootstrapTest_3(基础排板样式-2)
- html i标签
- JSTL取整、读取数组、字符串连接
- JQuery中ajax错误处理之页面跳转
- **JAVASCRIPT** DOM对象三
- 手机H5自适应布局
- javascript中对象写在函数外面,函数内部不能使用
- html scrip src
- Chrome开发者工具不完全指南(二、进阶篇)
- Chrome开发者工具不完全指南(一、基础功能篇)
- jsp基础
- 【转】让Bootstrap 3兼容IE8浏览器
- zookeeper可视化监控node-zk-browser
- UVALive 6100 Jugglefest Mid-Central USA 2012 模拟
- 剑指offer 4题 【字符串】替换空格
- jQuery技巧
- 【CSS进阶】伪元素的妙用2 - 多列均匀布局及title属性效果
- jquery插件讲解:轮播(SlidesJs)+验证(Validation)
- jQuery CSS 操作 - css() 方法