ObjectInputStream类readUTF()方法 (ObjectInputStream Class readUTF() method)
readUTF() method is available in java.io package.
readUTF()方法在java.io包中可用。
readUTF() method is used to read the string in an updated encoding scheme UTF-8 format.
readUTF()方法用于以更新的编码方案UTF-8格式读取字符串。
readUTF() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
readUTF()方法是一种非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
readUTF() method may throw an exception at the time of reading string.
readUTF()方法在读取字符串时可能会引发异常。
- IOException: This exception may throw when getting any input/output error while performing.IOException :在执行过程中遇到任何输入/输出错误时,可能引发此异常。
- UTFDataFormatExeption: This exception may throw when the read bytes denote invalid UTF-8 encoding of a string.UTFDataFormatExeption :当读取的字节表示字符串的无效UTF-8编码时,可能会引发此异常。
Syntax:
句法:
public String readUTF();
Parameter(s):
参数:
It does not accept any parameter.
它不接受任何参数。
Return value:
返回值:
The return type of the method is String, it returns the Unicode string.
该方法的返回类型为String ,它返回Unicode字符串。
Example:
例:
// Java program to demonstrate the example
// of String readUTF() method of
// ObjectInputStream
import java.io.*;
public class ReadUTFOfOIS {
public static void main(String[] args) throws Exception {
// Instantiates ObjectOutputStream , ObjectInputStream
// FileInputStream and FileOutputStream
FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
ObjectOutputStream obj_out_stm = new ObjectOutputStream(file_out_stm);
FileInputStream file_in_stm = new FileInputStream("D:\\includehelp.txt");
ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);
// By using writeUTF() method is to write
// the encoded string in UTF-8 to the
// obj_out_stm stream
obj_out_stm.writeUTF("JAVA");
obj_out_stm.writeUTF("C");
obj_out_stm.writeUTF("C++");
obj_out_stm.writeUTF("SFDC");
obj_out_stm.flush();
while (obj_in_stm.available() > 0) {
// By using readUTF() method is to read
// encoded string from the obj_in_stm
String val = (String) obj_in_stm.readUTF();
System.out.println("obj_in_stm.readUTF(): " + val);
}
// By using close() method is to
// close all the streams
file_in_stm.close();
file_out_stm.close();
obj_in_stm.close();
obj_out_stm.close();
}
}
Output
输出量
obj_in_stm.readUTF(): JAVA
obj_in_stm.readUTF(): C
obj_in_stm.readUTF(): C++
obj_in_stm.readUTF(): SFDC
翻译自: https://www.includehelp.com/java/objectinputstream-readutf-method-with-example.aspx