java 核心編程——IO流之字元流和位元組流相互轉換(四),io相互轉換
1.為什麼字元流和位元組流需要轉換?
這是因為有一些時候系統給你提供的只有位元組流,比如說System.in標準輸入資料流。就是位元組流。你想從他那裡得到使用者在鍵盤上的輸入,只能是以轉換流將它轉換為Reader以方便自己的程式讀取輸入。再比如說Socket裡的getInputStream()很明顯只給你提供位元組流,你要不行直接用,就得給他套個InputStreamReader()用來讀取。網路傳輸來的字元。
2.位元組流和字元流怎麼轉換?
2.1.位元組流轉換為字元流:InputStreamReader
2.2.字元輸流轉換為位元組流:InputStreamWriter
3.具體應用
3.1 位元組流轉換為字元流
package se.io;import java.io.*;public class InputStreamReaderTest { public static void main(String[] args) { try { //構建位元組輸入資料流對象 FileInputStream fileInputStream = new FileInputStream("E:\\test\\data3.txt"); //構建位元組字元轉換流對象 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); //構建字元輸入資料流對象 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); //讀取資料 char[] chars = new char[1024]; int off = 0; while(bufferedReader.ready()){ off = bufferedReader.read(chars); } //列印輸出 String s = new String(chars,0,off); System.out.println(s); //關閉流 bufferedReader.close(); inputStreamReader.close(); fileInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
3.2字元流轉換為位元組流
package se.io;import java.io.*;public class OutPutStreamWriterTest { public static void main(String[] args) { try { //構建輸出資料流位元組對象 FileOutputStream fileOutputStream = new FileOutputStream("E:\\test\\data4.txt"); //構建輸出資料流位元組字元轉換對象 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); //構建字元輸出資料流對象 BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); //構建資料 char[] chars = new char[3]; chars[0] = 'a'; chars[1] = 'b'; chars[2] = '中'; //輸出資料 bufferedWriter.write(chars); //關閉流 bufferedWriter.close(); outputStreamWriter.close(); fileOutputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}