我們能用 readUTF() 從 Java 中的 .txt 檔案讀取字串嗎?
java.io.DataOutputStream 的 readUTF() 方法將採用改良 UTF-8 編碼的資料讀入 String 中,並返回。
示例
下面的 Java 程式使用 readUTF() 方法從 .txt 檔案中讀取 UTF-8 文字。
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
public class UTF8Example {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer();
try {
//Instantiating the FileInputStream class
FileInputStream fileIn = new FileInputStream("D:\test.txt");
//Instantiating the DataInputStream class
DataInputStream inputStream = new DataInputStream(fileIn);
//Reading UTF data from the DataInputStream
while(inputStream.available()>0) {
buffer.append(inputStream.readUTF());
}
}
catch(EOFException ex) {
System.out.println(ex.toString());
}
catch(IOException ex) {
System.out.println(ex.toString());
}
System.out.println("Contents of the file: "+buffer.toString());
}
}輸出
Contents of the file: టుటోరియల్స్ పాయింట్ కి స్వాగతిం
使用 readUTF() 方讀取普通文字
如果使用 readUTF() 方法從檔案中讀取文字時,檔案內容不是無效的 UTF 格式,那麼此方法將生成 EOFException。
示例
在下面的 Java 程式中,我們使用 BufferedWriter 將普通文字寫入檔案,並嘗試使用 readUTF() 方法讀取它。這將生成 EOFException。
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import java.io.FileWriter;
public class ReadingTextUsingUTF {
public static void main(String args[]) {
FileWriter fileOut = null;
BufferedWriter bufferedWriter = null;
FileInputStream fileIn = null;
DataInputStream inputStream = null;
Scanner sc = new Scanner(System.in);
try {
//Instantiating the FileOutputStream class
fileOut = new FileWriter("D:\utfText.txt");
//Instantiating the DataOutputStream class
bufferedWriter = new BufferedWriter(fileOut);
//Writing UTF data to the output stream
System.out.println("Enter sample text (single line)");
bufferedWriter.write(sc.nextLine());
bufferedWriter.flush();
System.out.println("Data inserted into the file");
bufferedWriter.close();
fileOut.close();
//Instantiating the FileInputStream class
fileIn = new FileInputStream("D:\utfText.txt");
//Instantiating the DataInputStream class
inputStream = new DataInputStream(fileIn);
//Reading UTF data from the DataInputStream
while(inputStream.available()>0) {
System.out.println(inputStream.readUTF());
}
inputStream.close();
fileIn.close();
}
catch(EOFException ex) {
System.out.println("Contents are not in valid UTF-8 format");
}
catch(IOException ex) {
System.out.println(ex.toString());
}
}
}輸出
Enter sample text (single line) Hello how are you] Data inserted into the file Contents are not in valid UTF-8 format
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP