ObjectInputStream readUTF()方法

java.io.ObjectInputStream.readUTF() 方法在经修订的UTF-8格式读取一个字符串。

1 语法

public String readUTF()

2 参数

3 返回值

返回字符串。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.ObjectInputStream.readUTF()方法的例子
 */
import java.io.*;

public class Demo {
    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

热门文章

优秀文章