Java 教程

Java 控制语句

面向对象编程

Java 内置类

Java 文件处理

Java 错误和异常

Java 多线程

Java 同步

Java 网络

Java 集合

Java 接口

Java 数据结构

Java 集合算法

高级 Java

Java 杂项

Java API 和框架

Java 类参考

Java 有用资源

Java - 字节数组输入流



ByteArrayInputStream 类允许将内存中的缓冲区用作 InputStream。输入源是字节数组。

ByteArrayInputStream 类提供以下构造函数。

序号 构造函数和描述
1

ByteArrayInputStream(byte [] a)

此构造函数接受字节数组作为参数。

2

ByteArrayInputStream(byte [] a, int off, int len)

此构造函数采用字节数组和两个整数值,其中off 是要读取的第一个字节,len 是要读取的字节数。

一旦您拥有 ByteArrayInputStream 对象,则有一系列辅助方法可用于读取流或对流执行其他操作。

序号 方法和描述
1

public int read()

此方法从 InputStream 读取下一个数据字节。返回一个 int 作为下一个数据字节。如果它是文件末尾,则返回 -1。

2

public int read(byte[] r, int off, int len)

此方法从输入流中读取最多len 个字节,从off 开始,写入数组中。返回读取的字节总数。如果它是文件末尾,将返回 -1。

3

public int available()

给出可以从此文件输入流读取的字节数。返回一个 int,表示要读取的字节数。

4

public void mark(int read)

这将设置流中当前的标记位置。参数给出在标记位置失效之前可以读取的字节的最大限制。

5

public long skip(long n)

跳过流中的 'n' 个字节。这将返回实际跳过的字节数。

示例

以下示例演示了 ByteArrayInputStream 和 ByteArrayOutputStream。

import java.io.*;
public class ByteStreamTest {

   public static void main(String args[])throws IOException {
      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);

      while( bOutput.size()!= 10 ) {
         // Gets the inputs from the user
         bOutput.write("hello".getBytes()); 
      }
      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");
      
      for(int x = 0 ; x < b.length; x++) {
         // printing the characters
         System.out.print((char)b[x]  + "   "); 
      }
      System.out.println("   ");
      
      int c;
      ByteArrayInputStream bInput = new ByteArrayInputStream(b);
      System.out.println("Converting characters to Upper case " );
      
      for(int y = 0 ; y < 1; y++) {
         while(( c = bInput.read())!= -1) {
            System.out.println(Character.toUpperCase((char)c));
         }
         bInput.reset(); 
      }
   }
}

以下是上述程序的示例运行结果:

输出

Print the content
h   e   l   l   o   h   e   l   l   o      
Converting characters to Upper case 
H
E
L
L
O
H
E
L
L
O
java_files_io.htm
广告

© . All rights reserved.