转换流:从字节流转换到字符流

时间:2022-01-30 20:33:29

转换流:从字节流转换到字符流

EG:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class TestInputStreamReader {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  InputStreamReader in=new InputStreamReader(System.in);
  BufferedReader br=new BufferedReader(in);
  String str=null;
  try{
   while(br!=null){
    str=br.readLine();
    if(str.equalsIgnoreCase("exit"))break;
    System.out.println(str);
   }
  }catch(IOException e){
   e.printStackTrace();
  }
  
 }

}

EG:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

 

public class TestOutputStreamWriter {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try{
   //用程序默认的编码输出
   OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("D://wdl.txt"));
   osw.write("*");
   System.out.println(osw.getEncoding());
   osw.close();
   //用西欧编码输出中文会有乱码,true是在文件内容后追加
   //osw=new OutputStreamWriter(new FileOutputStream("D://wdl.txt",true),"ISO8859_1");
   osw=new OutputStreamWriter(new FileOutputStream("D://wdl.txt",true),"gb2312");
   osw.write("*");
   System.out.println(osw.getEncoding());
   osw.close();
  }catch(FileNotFoundException e){
   System.out.print("未找到文件");
  }catch(IOException e){
   System.out.println(e.getMessage());
  }
 }
}