📌  相关文章
📜  Java中的 ObjectInputStream read() 方法及示例

📅  最后修改于: 2022-05-13 01:55:14.343000             🧑  作者: Mango

Java中的 ObjectInputStream read() 方法及示例

Java中ObjectInputStream类的read()方法读取一个字节的数据。如果没有数据,此方法将不会运行。

语法

public int read()

参数:此方法不接受任何参数。

返回值:此方法返回读取的字节,如果到达流的末尾,则返回 -1。

异常:如果发生 I/O 错误,该函数将引发IOException

下面的程序说明了上述方法:

方案一:

// 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: Java/io/ObjectInputStream.html#read()