当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。