我们能用 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: టుటోరియల్స్ పాయింట్ కి స్వాగతిం
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
使用 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
广告