当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ObjectInputStream readUTF()用法及代码示例


ObjectInputStream 类的 readUTF() 方法用于读取 UTF(统一文本格式)格式的字符串。它以 UTF 格式返回从 objectinputstream 读取的字符串。

用法

public  String  readUTF()  throws  IOException

参数

NA

返回

字符串。

抛出

IOException

UTF数据格式异常

例子1

import java.io.*;

public class ObjectInputStreamreadUTFExample1 {
   public static void main(String[] args) {
      String str = "javaTpoint";
      
      try {
         FileOutputStream outstream = new FileOutputStream("file1.txt");
         ObjectOutputStream objoutstream = new ObjectOutputStream(outstream);
         //writing content inti file.
         objoutstream.writeUTF(str); 
         objoutstream.writeUTF("welcome to javatpoint");
         objoutstream.flush();
         ObjectInputStream objinstream= new ObjectInputStream(new FileInputStream("file1.txt"));
         //read the first line in textfile return  in UTF format
         System.out.println("" + objinstream.readUTF());
         //read the second line in textfile and return  in UTF format
         System.out.println("" + objinstream.readUTF());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

输出:

javaTpoint
welcome to javatpoint

例子2

import java.io.*; 
  
public class ObjectInputStreamreadUTFExample2 
{ 
    public static void main(String[] args) throws IOException, ClassNotFoundException 
    { 
        FileOutputStream outStream = new FileOutputStream("file1.txt"); 
        ObjectOutputStream objoutStream = new ObjectOutputStream(outStream); 
        ObjectInputStream objinStream  = new ObjectInputStream(new FileInputStream("file1.txt")); 
        objoutStream.writeUTF("Welcome to javaTpoint"); 
        objoutStream.flush(); 
        System.out.println("Use of readUTF():" + objinStream.readUTF()); 
    } 
}

输出:

Use of readUTF():Welcome to javaTpoint




相关用法


注:本文由纯净天空筛选整理自 Java ObjectInputStream readUTF() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。