目录

int read(byte[] b)

描述 (Description)

java.io.DataInputStream.read(byte[] b)方法从包含的输入流中读取字节数,并将它们分配到缓冲区b中。 该方法被阻止,直到输入数据可用,抛出异常或检测到文件结尾。

声明 (Declaration)

以下是java.io.DataInputStream.read(byte[] b)方法的声明 -

public final int read(byte[] b)

参数 (Parameters)

b - 从此流中读取数据的缓冲区数组。

返回值 (Return Value)

流中的总字节数,如果流已到达结束,则返回-1。

异常 (Exception)

  • IOException - 如果发生I/O错误,则无法读取第一个字节,或者在此方法之前调用close()。

  • NullPointerException - 如果b为null。

例子 (Example)

以下示例显示了java.io.DataInputStream.read(byte [] b)方法的用法。

package com.iowiki;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class DataInputStreamDemo {
   public static void main(String[] args) throws IOException {
      InputStream is = null;
      DataInputStream dis = null;
      try {
         // create input stream from file input stream
         is = new FileInputStream("c:\\test.txt");
         // create data input stream
         dis = new DataInputStream(is);
         // count the available bytes form the input stream
         int count = is.available();
         // create buffer
         byte[] bs = new byte[count];
         // read data into buffer
         dis.read(bs);
         // for each byte in the buffer
         for (byte b:bs) {
            // convert byte into character
            char c = (char)b;
            // print the character
            System.out.print(c+" ");
         }
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases any associated system files with this stream
         if(is!=null)
            is.close();
         if(dis!=null)
            dis.close();
      }   
   }
}

假设我们有一个文本文件c:/test.txt ,它具有以下内容。 这个文件将用作我们示例程序的输入 -

ABCDEFGH

让我们编译并运行上面的程序,这将产生以下结果 -

A B C D E F G H 
↑回到顶部↑
WIKI教程 @2018