Java中的ObjectInputStream類的read()方法讀取一個字節的數據。如果沒有數據,該方法將不會運行。
用法:
public int read()
參數:此方法不接受任何參數。
返回值:此方法返回讀取的字節,如果到達流的末尾,則返回-1。
異常注意:如果發生I /O錯誤,該函數將引發IOException。
以下示例程序旨在說明上述方法:
示例1:
// Java program to illustrate
// the above method
import java.io.*;
public class GFG {
public static void main(String[] args)
{
try {
// create a new file
// with an ObjectOutputStream
FileOutputStream out
= new FileOutputStream("gopal.txt");
ObjectOutputStream out1
= new ObjectOutputStream(out);
// write
out1.writeUTF("Geeks for Geeks");
// Flushes the stream
out1.flush();
// create an ObjectInputStream
// for the file
ObjectInputStream example
= new ObjectInputStream(
new FileInputStream(
"gopal.txt"));
// Read from the stream
for (int i = 0; i < example.available();) {
System.out.print("" + (char)example.read());
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
輸出:
參考: https://docs.oracle.com/javase/10/docs/api/java/io/ObjectInputStream.html#read()
相關用法
- Java ObjectInputStream available()用法及代碼示例
- Java ObjectInputStream close()用法及代碼示例
- Java ObjectInputStream readBoolean()用法及代碼示例
- Java CharArrayReader read()用法及代碼示例
- Java StringReader read()用法及代碼示例
- Java PushbackReader read()用法及代碼示例
- Java Reader read()用法及代碼示例
- Java CharArrayReader read(char[], int, int)用法及代碼示例
- Java CharArrayReader read(CharBuffer)用法及代碼示例
- Java PushbackReader read(char, int, int)用法及代碼示例
- Java StringReader read(char[])用法及代碼示例
- Java Reader read(CharBuffer)用法及代碼示例
- Java Reader read(char[], int, int)用法及代碼示例
- Java Reader read(char[])用法及代碼示例
- Java StringReader read(CharBuffer)用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 ObjectInputStream read() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。