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


Java ObjectInputStream readByte()用法及代碼示例


Java中ObjectInputStream類的readByte()方法用於讀取8位(字節)。

用法:

public byte readByte()

參數:此方法不接受任何參數。

返回值:此方法返回讀取的8位字節

錯誤和異常:該函數引發三個異常,如下所述:



  • EOFException:如果到達文件末尾,則會引發異常。
  • IOException:如果發生I /O錯誤,則會引發異常。

以下示例程序旨在說明上述方法:

程序1:

Java

// Java program to illustrate 
// the above method 
  
import java.io.*; 
  
public class GFG { 
  
    public static void main(String[] args) 
        throws IOException 
    { 
        byte[] array 
            = { 1, 34, 23, 
                42, 69, 22 }; 
  
        try { 
  
            // create new byte 
            // array input stream 
            InputStream input 
                = new ByteArrayInputStream(array); 
  
            // create data input stream 
            DataInputStream output 
                = new DataInputStream(input); 
  
            // readBoolean till the 
            // data available to read 
            while (output.available() > 0) { 
  
                // read one single byte 
                byte bt = output.readByte(); 
  
                // print the byte 
                System.out.print(bt + " "); 
            } 
        } 
  
        catch (Exception ex) { 
        } 
    } 
}

輸出:

程序2:

Java

// Java program to illustrate 
// the above method 
  
import java.io.*; 
  
public class GFG { 
  
    public static void main(String[] args) 
        throws IOException 
    { 
        byte[] array 
            = { 'G', 'e', 'e', 'k', 
                's', 'f', 'o', 'r', 
                'g', 'e', 'e', 'k', 
                's' }; 
  
        try { 
  
            // create new byte 
            // array input stream 
            InputStream input 
                = new ByteArrayInputStream(array); 
  
            // create data input stream 
            DataInputStream output 
                = new DataInputStream(input); 
  
            // readBoolean till the 
            // data available to read 
            while (output.available() > 0) { 
  
                // read one single byte 
                byte bt = output.readByte(); 
  
                // print the byte 
                System.out.print(bt + " "); 
            } 
            System.out.println(); 
            System.out.println(); 
        } 
  
        catch (Exception ex) { 
        } 
    } 
}

輸出:

參考:

https://docs.oracle.com/javase/10/docs/api/java/io/ObjectInputStream.html#readByte()




相關用法


注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 ObjectInputStream readByte() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。