需求:创建一个文本文件,以UTF-8高效写入,并高效读取。
1 package com.day506.IO; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.FileOutputStream; 8 import java.io.IOException; 9 import java.io.InputStreamReader; 10 import java.io.OutputStreamWriter; 11 12 //创建一个文本文件,以UTF-8高效写入一首诗,并高效读取。 13 public class IO1 { 14 public static void main(String[] args) throws IOException { 15 16 File file = new File("e:\\Test\\a.txt"); 17 if (!file.exists()) { 18 boolean r; 19 try { 20 r = file.createNewFile(); 21 if (r) { 22 System.out.println("创建文件成功"); 23 } 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } 27 } 28 String str = "雨打梨花深闭门"; 29 // 创建管道 30 FileOutputStream out = new FileOutputStream(file); 31 OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); 32 BufferedWriter bw = new BufferedWriter(writer); 33 // 写入管道 34 bw.write("\t" + str); 35 bw.newLine(); 36 bw.write("\t " + "唐寅(明)"); 37 bw.newLine(); 38 // bw.write("\r\n"); 39 bw.write("雨打梨花深闭门,忘了青春,误了青春。"); 40 bw.newLine(); 41 // bw.write("\r\n"); 42 bw.write("赏心乐事共谁论?花下销魂,月下销魂。"); 43 bw.write("\r\n"); 44 // bw.newLine(); 45 bw.write("愁聚眉峰尽日颦,千点啼痕,万点啼痕。"); 46 bw.write("\r\n"); 47 // bw.newLine(); 48 bw.write("晓看天色暮看云,行也思君,坐也思君。"); 49 bw.newLine(); 50 // bw.write("\r\n"); 51 // 刷新缓冲区 52 bw.flush(); 53 // 关闭管道 54 out.close(); 55 writer.close(); 56 System.out.println("写入文件成功"); 57 // 高效读取 58 // 创建管道 59 60 FileInputStream in = new FileInputStream(file); 61 // 以"UTF-8"编码,就必须以"UTF-8"解码。 62 InputStreamReader reader = new InputStreamReader(in, "UTF-8"); 63 BufferedReader br = new BufferedReader(reader); 64 // 读取文件 65 String line; 66 while ((line = br.readLine()) != null) { 67 System.out.println(line); 68 } 69 // 关闭管道 70 in.close(); 71 reader.close(); 72 } 73 }