Java IO流--字节字符转换流
转换流:可以将字节流转换成字符流,也可以将字符流转换成字节流。
InputStreamReader:将输入的字节流转换成字符流
OutputStreamWriter:将输出的字符流转换成字节流
代码示例:
package com.seven.javaSE; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; public class ChangeStream { public static void main(String[] args) { InputStream in=null; try { in = new FileInputStream("c:/TestFile/hello.txt"); read(in); } catch (FileNotFoundException e) { e.printStackTrace(); } try { OutputStream out = new FileOutputStream("C:/TestFile/target.txt"); write(out); } catch (FileNotFoundException e) { e.printStackTrace(); } } //输入字节流转成字符流 public static void read(InputStream in) { Reader reader = new InputStreamReader(in,Charset.defaultCharset()); StringBuilder sb = new StringBuilder(); char [] content = new char[10]; int len=-1; try { while((len=reader.read(content))!=-1) { sb.append(content,0,len); } reader.close(); System.out.println(sb); } catch (IOException e) { e.printStackTrace(); } } //输出字符流转成字节流 public static void write(OutputStream out) { Writer writer = new OutputStreamWriter(out,Charset.defaultCharset()); try { writer.write("藤原豆腐渣渣学Java"); } catch (IOException e) { e.printStackTrace(); } try { writer.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("写入文件成功"); } }
本文来自博客园,作者:藤原豆腐渣渣,转载请注明原文链接:https://www.cnblogs.com/javafufeng/p/16385031.html