📜  Java I/O-ByteArrayInputStream

📅  最后修改于: 2020-09-27 02:31:22             🧑  作者: Mango

Java ByteArrayInputStream类

ByteArrayInputStream由两个词组成:ByteArray和InputStream。顾名思义,它可用于读取字节数组作为输入流。

Java ByteArrayInputStream类包含一个内部缓冲区,该缓冲区用于读取字节数组作为流。在此流中,从字节数组中读取数据。

ByteArrayInputStream的缓冲区根据数据自动增长。

Java ByteArrayInputStream类声明

让我们看一下Java.io.ByteArrayInputStream类的声明:

public class ByteArrayInputStream extends InputStream

Java ByteArrayInputStream类构造函数

Constructor Description
ByteArrayInputStream(byte[] ary) Creates a new byte array input stream which uses ary as its buffer array.
ByteArrayInputStream(byte[] ary, int offset, int len) Creates a new byte array input stream which uses ary as its buffer array that can read up to specified len bytes of data from an array.

Java ByteArrayInputStream类方法

Methods Description
int available() It is used to return the number of remaining bytes that can be read from the input stream.
int read() It is used to read the next byte of data from the input stream.
int read(byte[] ary, int off, int len) It is used to read up to len bytes of data from an array of bytes in the input stream.
boolean markSupported() It is used to test the input stream for mark and reset method.
long skip(long x) It is used to skip the x bytes of input from the input stream.
void mark(int readAheadLimit) It is used to set the current marked position in the stream.
void reset() It is used to reset the buffer of a byte array.
void close() It is used for closing a ByteArrayInputStream.

Java ByteArrayInputStream的示例

让我们看一下java ByteArrayInputStream类的简单示例,以读取字节数组作为输入流。

package com.javatpoint;
import java.io.*;
public class ReadExample {
  public static void main(String[] args) throws IOException {
    byte[] buf = { 35, 36, 37, 38 };
    // Create the new byte array input stream
    ByteArrayInputStream byt = new ByteArrayInputStream(buf);
    int k = 0;
    while ((k = byt.read()) != -1) {
      //Conversion of a byte into character
      char ch = (char) k;
      System.out.println("ASCII value of Character is:" + k + "; Special character is: " + ch);
    }
  }
}

输出:

ASCII value of Character is:35; Special character is: #
ASCII value of Character is:36; Special character is: $
ASCII value of Character is:37; Special character is: %
ASCII value of Character is:38; Special character is: &