1 package file; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.InputStreamReader; 10 import java.io.OutputStreamWriter; 11 12 /* 13 转换流: 14 15 输入字节流的转换流: 16 InputStreamReader是字节流通向字符流的桥梁 17 输出字节流的转换流: 18 OutputStreamWriter是字节流通向字符流的桥梁 19 20 转换流的作用: 21 字节流---->字符流 22 23 24 */ 25 public class Demo12 { 26 public static void main(String[] args) throws IOException { 27 // readTest(); 28 // writeTest(); 29 // writeTest2(); 30 readTest2(); 31 } 32 33 //使用输入字节流的转换流 指定码表读取数据 34 public static void readTest2() throws IOException { 35 File file = new File("F:\a.txt"); 36 //建立数据输入通道 37 FileInputStream fileInputStream = new FileInputStream(file); 38 //把输入字节流转换 并且指定码表 39 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8"); 40 char[] buf = new char[1024]; 41 int length = 0; 42 while((length = inputStreamReader.read(buf))!=-1) { 43 System.out.println(new String(buf,0,length)); 44 } 45 inputStreamReader.close(); 46 } 47 48 49 //使用输出字节流的转换流 指定码表写出数据 50 public static void writeTest2() throws IOException { 51 File file = new File("F:\a.txt"); 52 //建立数据输出通道 53 FileOutputStream fileOutputStream = new FileOutputStream(file); 54 //把输出字节流转换成字符流并且指定码表 55 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8"); 56 outputStreamWriter.write("ab哈哈哈"); 57 //关闭资源 58 outputStreamWriter.close(); 59 60 } 61 62 // 输出字节流的转换流: 63 public static void writeTest() throws IOException { 64 File file = new File("F:\a.txt"); 65 FileOutputStream fileOutputStream = new FileOutputStream(file); 66 //输出字节流转换成字符流 67 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); 68 69 outputStreamWriter.write("hello大家好"); 70 outputStreamWriter.close(); 71 } 72 73 74 // 输入字节流的转换流: 字节流---->字符流 75 public static void readTest() throws IOException { 76 InputStream in = System.in; 77 //需要把字节流转换成字符流 78 InputStreamReader inputStreamReader = new InputStreamReader(in); 79 //使用字符流的缓冲类 80 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 81 82 String line = null; 83 while((line = bufferedReader.readLine())!= null) { 84 System.out.println("内容:" + line); 85 } 86 bufferedReader.close(); 87 } 88 }