Java.io.ObjectInputStream.readUTF()方法实例
java.io.ObjectInputStream.readUTF() 方法在经修订的UTF-8格式读取一个字符串。
声明
以下是java.io.ObjectInputStream.readUTF()方法声明
public String readUTF()
参数
-
NA
返回值
此方法返回字符串。
异常
-
UTFDataFormatException -- 如果读取的字节不表示一个字符串的一个有效的经修订的UTF-8编码
-
IOException --如果从基础InputStream读取有I / O错误
例子
下面的示例演示java.io.ObjectInputStream.readUnsignedShort()方法的用法。
package com.yiibai; import java.io.*; public class ObjectInputStreamDemo { public static void main(String[] args) { String s = "Hello World!"; try { // create a new file with an ObjectOutputStream FileOutputStream out = new FileOutputStream("test.txt"); ObjectOutputStream oout = new ObjectOutputStream(out); // write something in the file oout.writeUTF(s); oout.writeUTF("This is an example"); oout.flush(); // create an ObjectInputStream for the file we created before ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt")); // read and print the string System.out.println("" + ois.readUTF()); // read and print the string System.out.println("" + ois.readUTF()); } catch (Exception ex) { ex.printStackTrace(); } } }
让我们编译和运行上面的程序,这将产生以下结果:
Hello World! This is an example