【java】io流之字节流转为字符流:java.io.OutputStreamWriter和java.io.InputStreamReader
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package 文件操作; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 import java.io.OutputStreamWriter; 8 9 public class TestOutputStreamWriter { 10 public static void main(String[] args) throws IOException { 11 File file=new File("D:"+File.separator+"test.txt"); 12 OutputStream out =new FileOutputStream(file);//若文件不存在会自动创建 13 //字节流转换为字符流。文件内容本质上都是以字节形式在操作系统里操作的,处理中文时需要在缓冲区进行隐式转换 14 OutputStreamWriter outputStreamWriter=new OutputStreamWriter(out); 15 String str="Welcom!中国"; 16 outputStreamWriter.write(str); 17 // outputStreamWriter.flush();//通过flush()或close()操作后内容才会被写进文件 18 outputStreamWriter.close(); 19 } 20 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package 文件操作; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.InputStreamReader; 8 9 public class TestInputStreamReader { 10 public static void main(String[] args) throws IOException { 11 File file=new File("D:"+File.separator+"com"+File.separator+"test.txt"); 12 char[] chars=new char[1024]; 13 if(file.exists()){ 14 // file.getParentFile().mkdirs();//建议使用mkdirs而不要用mkdir,mkdirs既能创建单级目录又能创建多级目录,mkdir只能创建单级目录 15 // file.createNewFile(); 16 InputStream in=new FileInputStream(file); 17 InputStreamReader inputStreamReader=new InputStreamReader(in); 18 int len=inputStreamReader.read(chars); 19 System.out.println("*"+new String(chars,0,len)+"*"); 20 inputStreamReader.close(); 21 } 22 } 23 }