當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。