编码:把字符串转换成字节数组 解码:把字节数组转换成字符串
package org.org.westos.demo; import java.io.UnsupportedEncodingException; public class MyClass { public static void main(String[] args) throws UnsupportedEncodingException { //使用平台默认的编码表进行编解码 //编码 byte[] bytes = "好好学习,天天向上".getBytes(); //解码 String s = new String(bytes); System.out.println(s); //指定编码表进行编解码 //编码 byte[] bytes1 = "爱生活,爱Java".getBytes("GBK"); //解码 String str = new String(bytes1, "GBK"); System.out.println(str); //如果编解码用的编码表不一致,就会出现乱码 String s1 = new String(bytes1, "UTF-8"); System.out.println(s1); } }当然,子类还有其他的,主要学习InputStreamReader和OutputStreamWriter
InputStreamReader和OutputStreamWriter的综合应用:赋值文本文件 (1)读一个字符,写一个字符
package org.org.westos.demo; import java.io.*; public class MyClass { public static void main(String[] args) throws IOException { //复制文本文件,并读一个字符,写一个字符 InputStreamReader in = new InputStreamReader(new FileInputStream("a.txt")); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("b.txt")); //定义一个字符,记录读取的每个字符 int ch = 0; while((ch=in.read())!=-1){ out.write(ch); out.flush(); } in.close(); out.close(); } }(2)读一个字符数组,写一个字符数组
package org.org.westos.demo; import java.io.*; public class MyClass { public static void main(String[] args) throws IOException { //复制文本文件,并读一个字符数组,写一个字符数组 InputStreamReader in = new InputStreamReader(new FileInputStream("a.txt")); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("c.txt")); //定义一个字符,记录读取的每个字符 int ch = 0; //创建一个字符数组,充当缓冲区 char[] chars = new char[1024]; while((ch=in.read(chars))!=-1){ out.write(chars,0,ch); out.flush(); } in.close(); out.close(); } }上面几个代码流的处理都是直接抛给虚拟机,我们也可以自己处理,即通过try,catch
package org.org.westos.demo; import java.io.*; public class MyClass { public static void main(String[] args) { InputStreamReader in=null; OutputStreamWriter out=null; try{ //复制文本文件,并读一个字符数组,写一个字符数组 in = new InputStreamReader(new FileInputStream("a.txt")); out = new OutputStreamWriter(new FileOutputStream("c.txt")); //定义一个字符,记录读取的每个字符 int ch = 0; //创建一个字符数组,充当缓冲区 char[] chars = new char[1024]; while((ch=in.read(chars))!=-1){ out.write(chars,0,ch); out.flush(); } }catch (IOException e){ e.printStackTrace(); }finally { try{ if(in!=null){ in.close(); } if(out!=null){ out.close(); } }catch (IOException e){ e.printStackTrace(); } } } }与字符流的关系: 注:便捷字符流与它的父类用法一摸一样,唯一的弊端就是不能指定码表,只能使用平台默认码表
高效字符流跟高效字节流一样,效果是一样的,就是达到了高效的效果
至此,了解了字节流和字符流,那么,什么情况下使用那种流呢? 如果数据所在的文件通过windows自带的记事本打开并能读懂内容,就用字符流,其他用字节流 如果什么都不知道,就用字节流,因为字节流可以读写任何类型文件