Java中的Java.io.OutputStream类用法介绍

2021年3月15日09:32:13 发表评论 644 次浏览

此抽象类是表示字节输出流的所有类的超类。输出流接受输出字节并将其发送到某个接收器。

需要定义OutputStream子类的应用程序必须始终至少提供一种写入一个字节输出的方法。

构造函数和描述

  • OutputStream():单一构造器

方法:

  • void close():关闭此输出流并释放与此流关联的所有系统资源。
    Syntax :public void close()
               throws IOException
    Throws:
    IOException
  • void flush():刷新此输出流, 并强制写出所有缓冲的输出字节。
    Syntax :public void flush()
               throws IOException
    Throws:
    IOException
  • void write(byte [] b):将指定字节数组中的b.length个字节写入此输出流。
    Syntax :public void write(byte[] b)
               throws IOException
    Parameters:
    b - the data.
    Throws:
    IOException 
  • void write(byte [] b, int off, int len):从指定的字节数组开始将len个字节从offset偏移量写入此输出流。
    Syntax :public void write(byte[] b, int off, int len)
               throws IOException
    Parameters:
    b - the data.
    off - the start offset in the data.
    len - the number of bytes to write.
    Throws:
    IOException 
  • abstract void write(int b):将指定的字节写入此输出流。
    Syntax :public abstract void write(int b)
                        throws IOException
    Parameters:
    b - the byte.
    Throws:
    IOException
import java.io.*;
//Java program to demonstrate OutputStream
class OutputStreamDemo
{
     public static void main(String args[]) throws Exception
     {
         OutputStream os = new FileOutputStream( "file.txt" );
         byte b[] = { 65 , 66 , 67 , 68 , 69 , 70 };
          
         //illustrating write(byte[] b) method
         os.write(b);
          
         //illustrating flush() method
         os.flush();
  
         //illustrating write(int b) method
         for ( int i = 71 ; i < 75 ; i++) 
         {
             os.write(i);
         }
          
         os.flush();
          
         //close the stream
         os.close();
     }
}

输出:

ABCDEFGHIJ

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: