The java.io.ObjectInputStream class is a class in Java that provides an input stream for reading Java objects that have previously been serialized using the ObjectOutputStream class. One of the methods provided by this class is readUTF(), which is used to read a String value from the underlying input stream.
Examples:
Example 1: Reading a String value from an ObjectInputStream
import java.io.*;
public class Example1 {
public static void main(String[] args) {
try {
FileInputStream fileIn = new FileInputStream("object.ser"); ObjectInputStream in = new ObjectInputStream(fileIn);
String str = in.readUTF();
System.out.println(str);
in.close(); fileIn.close();
} catch(IOException i) {
i.printStackTrace();
} catch(ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
} } }
In this example, a String value is read from an ObjectInputStream using the readUTF() method. The ObjectInputStream is created from a FileInputStream that reads from a file called "object.ser". The readUTF() method is used to read the String value from the input stream and store it in a variable called "str". Finally, the value of "str" is printed to the console.
Package Library: java.io
Example 2: Reading multiple String values from an ObjectInputStream
import java.io.*;
public class Example2 {
public static void main(String[] args) {
try {
FileInputStream fileIn = new FileInputStream("object.ser"); ObjectInputStream in = new ObjectInputStream(fileIn);
while(true) {
String str = in.readUTF();
System.out.println(str);
}
} catch(EOFException e) {
System.out.println("End of file");
} catch(IOException i) {
i.printStackTrace();
} catch(ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
} } }
In this example, multiple String values are read from an ObjectInputStream using the readUTF() method inside a while loop. The loop continues until an EOFException is caught, indicating the end of the input stream. Each String value is printed to the console as it is read from the input stream.
Package Library: java.io
Java ObjectInputStream.readUTF - 30 examples found. These are the top rated real world Java examples of java.io.ObjectInputStream.readUTF extracted from open source projects. You can rate examples to help us improve the quality of examples.