zoukankan      html  css  js  c++  java
  • Java IO ---学习笔记(InputStream 和 OutputStream)

    基类: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);
        }
    }

    执行的结果:

  • 相关阅读:
    段间跳转之陷阱门
    段间跳转之中断门
    段间跳转之调用门
    代码段段间跳转流程
    Window内核学习之保护模式基础
    回顾2020,展望2021
    内存管理之堆
    Windows进程间通讯(IPC)----信号量
    线程本地存储(动态TLS和静态TLS)
    Windows进程间通讯(IPC)----套接字
  • 原文地址:https://www.cnblogs.com/silianbo/p/4666373.html
Copyright © 2011-2022 走看看