概念

Java既支持字节流,又支持字符流,但是有时我们可能同时需要使用到字节流和字符流。那么如何在字节流和字符流之间相互转换?此时就需要使用 转换流!

Java提供的转换流:

InputStreamReader、OutputStreamWrite
InputStreamReader:将字节流中的字节 可以转换为 字符
OutputStreamWrite:将字符流中的字符 转换为 字节

原理图

交换流(了解) - 图1
public class TestTransfer {
public static void main(String[] args) throws IOException {

OutputStreamWriter osw = null;
InputStreamReader isr = null;

  1. File srcf = new File("E:\\log\\TestPrint.java");<br /> File dief = new File("E:\\logs\\spring111.java");<br /> if(!dief.exists()) {<br /> dief.createNewFile();<br /> }
  2. try {<br /> isr = new InputStreamReader(new FileInputStream(srcf));<br /> osw = new OutputStreamWriter(new FileOutputStream(dief));<br /> char[] cs = new char[100];<br /> int len = isr.read(cs, 0, cs.length);<br /> while(len != -1){<br /> osw.write(cs, 0, len);<br /> len = isr.read(cs, 0, cs.length);<br /> }<br /> } catch (FileNotFoundException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> } catch (IOException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> }finally {<br /> osw.close();<br /> isr.close();<br /> }<br /> }<br />}