Java I/O系统之Reader

来源:互联网 发布:韩都衣舍淘宝 编辑:程序博客网 时间:2024/09/21 06:38

1.Reader类型

继承自Reader的流都是用于向程序中输入数据,且数据的单位为字符(16bit);下图中深色为节点流,浅色的为处理流。


2.Reader的基本方法

1)        读取一个字符并以整数形式返回(0~255),如果返回-1已到输入流的末尾。

[java] view plain copy
print?
  1. int read() throws IOException  

2)        读取一系列字符并存储到一个数组buffer,返回实际读取的字符数,如果读取前已到输入流的末尾返回-1

[java] view plain copy
print?
  1. int read(char[] cbuf) throws IOException  

3)        读取length个字符,并存储到一个数组buffer,从length位置开始返回实际读取的字符数,如果读取前输入流的末尾返回-1.

[java] view plain copy
print?
  1. int read(char[] cbuf, int offset, int length) throws IOException  

4)        关闭流释放内存资源

[java] view plain copy
print?
  1. void close() throws IOException  

5)        跳过n个字符不读,返回实际跳过的字节数

[java] view plain copy
print?
  1. long skip(long n) throws IOException  

3.Reader例子

[java] view plain copy
print?
  1. package com.owen.io;  
  2.   
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileReader;  
  5. import java.io.IOException;  
  6.   
  7. /** 
  8.  * 读取文件 FileReader 
  9.  * @author OwenWilliam 2016-7-19 
  10.  * @since 
  11.  * @version v1.0.0 
  12.  * 
  13.  */  
  14. public class TestFileReader  
  15. {  
  16.   
  17.     public static void main(String[] args)  
  18.     {  
  19.         FileReader fr = null;  
  20.         int c = 0;  
  21.           
  22.         try  
  23.         {  
  24.             fr = new FileReader("E:/workspace/Java/IO/src/com/owen/io/TestFileReader.java");  
  25.             int ln = 0;  
  26.             while ((c = fr.read()) != -1)  
  27.             {  
  28.                 //char ch = (char) fr.read();  
  29.                 System.out.print((char) c);  
  30.                 /*if (++ln >= 100) 
  31.                 { 
  32.                     System.out.println(); 
  33.                     ln = 0; 
  34.                 }*/  
  35.             }  
  36.         } catch (FileNotFoundException e)  
  37.         {  
  38.             System.out.println("文件找不到");  
  39.         }catch (IOException e)  
  40.         {  
  41.             System.out.println("文件读取错误");  
  42.         }  
  43.     }  
  44.   
  45. }  








原创粉丝点击