Java I/O系统之InputStream

来源:互联网 发布:百川软件怎么样 编辑:程序博客网 时间:2024/06/18 17:01

1.InputStream类型

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


2.InputStream的基本方法

InputStream的有以下几个的基本用法:

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(byte[] buffer) throws IOException  

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

[java] view plain copy
print?
  1. int read(byte[] buffer, 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.InputStream的例子

[java] view plain copy
print?
  1. package com.owen.io;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6.   
  7. /** 
  8.  * 读取文件 FileInputStream 
  9.  * @author OwenWilliam 2016-7-19 
  10.  * @since 
  11.  * @version v1.0.0 
  12.  * 
  13.  */  
  14. public class TestFileInputStream  
  15. {  
  16.   
  17.     public static void main(String[] args)  
  18.     {  
  19.         int b = 0;  
  20.         FileInputStream in = null;  
  21.         try  
  22.         {  
  23.             in = new FileInputStream("E:\\workspace\\Java\\IO\\src\\com\\owen\\io\\TestFileInputStream.java");  
  24.         }   
  25.         catch (FileNotFoundException e)  
  26.         {  
  27.             System.out.println("找不到指定文件");  
  28.             System.exit(-1);  
  29.         }  
  30.           
  31.         try  
  32.         {  
  33.             long num = 0;  
  34.             while ((b = in.read()) != -1)  
  35.             {  
  36.                 System.out.print((char)b);  
  37.                 num++;  
  38.             }  
  39.               
  40.             in.close();  
  41.             System.out.println();  
  42.             System.out.println("其读取了 " + num + " 个字节");  
  43.         }  
  44.         catch (IOException el)  
  45.         {  
  46.             System.out.println("文件读取错误");  
  47.             System.exit(-1);  
  48.         }  
  49.   
  50.     }  
  51.   
  52. }