1. 程式人生 > 實用技巧 >JavaIO流-轉換流

JavaIO流-轉換流

import org.junit.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 處理流之二:轉換流
 *
 * 1.InputStreamReader\OutputStreamWriter(看字尾:字元流)
 * 2.讀寫使用char陣列
 * 3.作用:提供位元組流與字元流之間的轉換
 * InputStreamReader:將一個位元組輸入流轉換為字元輸入流
 * OutputStreamWriter:將一個字元輸出流轉換為位元組流
 *
 * 3.位元組、位元組陣列  --->字元陣列、字串(解碼)
 *   字元陣列、字串 --->位元組、位元組陣列 (編碼)
 *
 * 4.字符集
 *
 *
 * 
@author orz */ public class IOStreamReaderWriter { @Test public void test()throws IOException { InputStreamReader isr; OutputStreamWriter osw; File file1=new File("hello.txt"); FileInputStream fis=new FileInputStream(file1); //引數2指明瞭字符集,具體使用哪個字符集取決於檔案儲存時使用的字符集
// isr=new InputStreamReader(fis, StandardCharsets.UTF_8); isr=new InputStreamReader(fis); // isr=new InputStreamReader(fis, "GBK"); char [] cbuf=new char[1024]; int len; while ((len=isr.read(cbuf))!=-1) { String str=new String(cbuf,0,len); System.out.print(str); } isr.close();
//osw.close(); } /** * * 綜合使用 */ @Test public void test2()throws IOException { InputStreamReader isr; OutputStreamWriter osw; File file1=new File("hello.txt"); File file2=new File("hi.txt"); FileInputStream fis=new FileInputStream(file1); FileOutputStream fos=new FileOutputStream(file2); //引數2指明瞭字符集,具體使用哪個字符集取決於檔案儲存時使用的字符集 isr=new InputStreamReader(fis,"utf-8"); //isr=new InputStreamReader(fis); // isr=new InputStreamReader(fis, "GBK"); osw=new OutputStreamWriter(fos,"gbk"); char [] cbuf=new char[1024]; int len; while ((len=isr.read(cbuf))!=-1) { osw.write(cbuf,0,len); } isr.close(); osw.close(); } }