當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.io.DataInputStream.read()用法及代碼示例


描述

這個java.io.DataInputStream.read(byte[] b, int off, int len)方法讀取len包含的輸入流中的字節並將它們分配到緩衝區 b 中,從b[off].該方法被阻塞,直到輸入數據可用、拋出異常或檢測到文件結尾。

聲明

以下是聲明java.io.DataInputStream.read(byte[] b, int off, int len)方法 -

public final int read(byte[] b, int off, int len)

參數

  • b- 從輸入流中讀取數據的字節[]。

  • off- b[] 中的起始偏移量。

  • len− 讀取的最大字節數。

返回值

讀取的總字節數,如果流已到達末尾,則為 -1。

異常

  • IOException− 如果發生I/O 錯誤,則無法讀取第一個字節,或在此方法之前調用close()。

  • NullPointerException− 如果 b 為空。

  • IndexOutOfBoundsException- 如果 len 大於 b.length - off,off 為負,或 len 為負

示例

下麵的例子展示了 java.io.DataInputStream.read(byte[] b, int off, int len) 方法的用法。

package com.tutorialspoint;

import java.io.DataInputStream;
import java.io.FileInputStream;
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 len data into buffer starting at off
         dis.read(bs, 4, 3);
         
         // for each byte in the buffer
         for (byte b:bs) {
         
            // convert byte into character
            char c = (char)b;
            
            // empty byte as char '0'
            if(b == 0)
               c = '0';
            
            // 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

讓我們編譯並運行上麵的程序,這將產生以下結果 -

0000ABC0

相關用法


注:本文由純淨天空篩選整理自 Java.io.DataInputStream.read() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。