Java IO ---学习笔记(InputStream 和 OutputStream)

来源:互联网 发布:基于粒子群算法的论文 编辑:程序博客网 时间:2024/05/21 10:13
基类:InputStream 和 OutputStream

字节流主要操作byte类型数据,以byte数组为准,java 中每一种字节流的基本功能依赖于基本类 InputStream 和 Outputstream,他们是抽象类,不能直接使用。

  InputStream 是所有表示位输入流的父类,继承它的子类要重新定义其中所定义的抽象方法。InputStream 是从装置来源地读取数据的抽象表 示,例如 System 中的标准输入流 in 对象就是一个 InputStream 类型的实例。

我们先来看看 InputStream 类的方法:

方法说明read()throws IOException从流中读入数据skip()throws IOException跳过流中若干字节数available()throws IOException返回流中可用字节数mark()throws IOException在流中标记过的位置reset()throws IOException返回标记过的位置markSupport()throws IOException是否支持标记和复位操作close()throws IOException关闭流

  在 InputStream 类中,方法 read() 提供了三种从流中读数据的方法:

  1. int read():从输入流中读一个字节,形成一个0~255之间的整数返回(是一个抽象方法)
  2. int read(byte b[]):读多个字节到数组中,填满整个数组
  3. int read(byte b[],int off,int len):从输入流中读取长度为 len 的数据,写入数组 b 中从索引 off 开始的位置,并返回读取得字节数。

  对于这三个方法,若返回-1,表明流结束,否则,返回实际读取的字符数。

  OutputStream 是所有表示位输出流的类之父类。子类要重新定义其中所定义的抽象方法,OutputStream 是用于将数据写入目的地的抽象表示。例如 System 中的标准输出流对象 out 其类型是java.io.PrintStream,这个类是 OutputStream 的子类

OutputStream类方法:

方法说明write(int b)throws IOException将一个整数输出到流中(只输出低位字节,为抽象方法)write(byte b[])throws IOException将字节数组中的数据输出到流中write(byte b[], int off, int len)throws IOException将数组 b 中从 off 指定的位置开始,长度为 len 的数据输出到流中flush()throws IOException刷空输出流,并将缓冲区中的数据强制送出close()throws IOException关闭流

看个例子吧:

import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;/** * * @author silianbo */public class test {    /**     *把输入流中的所用内容赋值带输出流中去     * @param in     * @param out     * @throws TOExcepetion     */    public void copy(InputStream in,OutputStream out)throws IOException{    byte[]buf= new byte[4093];    int len = in.read(buf);            while (len!=-1) {                        out.write(buf,0,len);            len=in.read(buf);        }    }    public static void main(String[] args) throws IOException {        test t= new test();        System.out.println("输入字符:");        t.copy(System.in, System.out);    }}

执行的结果:

阅读全文
0 0
原创粉丝点击