字符流1

为什么出现字符流

     因为字节流操作中文不是特别方便,所以提供字符流

           字符流=字节流+编码表

字符串中编码

byte[] getBytes()  使用平台的默认字符集将该String编码为一系列字节,将结果存储到新的字节数组中

byte[] getBytes(String charsetName)使用指定的字符集将该String编码为一系列字节,将结果存储到新的字节数组中

字符串中解码

String(byte[] bytes) 通过使用平台的默认字符集解码指定的字节数组来构造新的String

String(byte[] bytes,String charsetName) 通过指定的字符集解码指定的字节数组来构造新的String

 

public class StringDemo{

   public static void main(String[] args)throws UnsupportedEncodingException{

    String s="中国";

    byte[] bys=s.getBytes();

    System.out.println(Arrays.toString(bys));

    String ss=new String(bys);

    System.out.println(ss);

     

}

}

字符流中编码

InputStreamReader

是从字节流到字符流的桥梁,它读取字节,并使用指定的编码将其解码为字符,它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集

 

字符流中解码

OutputStreamWriter

是从字符流到字节流的桥梁,使用指定的编码将写入的字符编码为字节,它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集

public class ConversionStreamDemo{

public static void main(String[] args)throws IOException{

OutputStreamWriter osw=new OutputStreamWriter(new FiieOutputStream("mychar\\osw.txt"));

osw.write("中国");

osw.close();

InputStreamReader isr=new InputStreamReader(new FileInputStream("mychar\\osw.txt"))

int ch;

while((ch=isr.read())!=-1){

   System.out.println((char)ch);

    isr.close();

}

}

}                                

 

posted @ 2021-09-29 17:34  Cuora  阅读(34)  评论(0)    收藏  举报