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