转换流
InputStreamReader
OutputStreamWriter
属于 1.处理流 2.字符流
作用:用来转换 字节流到字符流,或者字符流到字节流

从字节流读成字符流 输出到控制台

  1. package com.daijunyi.file;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. /**
  6. *转换流
  7. * InputStreamReader
  8. * OutputStreamWriter
  9. *
  10. * 属于 1.处理流 2.字符流
  11. * 作用:用来转换 字节流到字符流,或者字符流到字节流
  12. * */
  13. public class InputStreamReaderTest {
  14. public static void main(String[] args) {
  15. InputStreamReader isr = null;//属于直接用默认的编码集
  16. try {
  17. FileInputStream fis = new FileInputStream("hello.txt");
  18. isr = new InputStreamReader(fis);
  19. char[] buffer = new char[10];
  20. int len;
  21. while ((len = isr.read(buffer)) != -1){
  22. System.out.print(new String(buffer,0,len));
  23. }
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. } finally {
  27. try {
  28. if (isr != null){
  29. isr.close();
  30. }
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. }
  36. }

utf-8格式的文本文件,转换成gbk编码的文本文件

package com.daijunyi.file;

import java.io.*;

public class OutputStreamWriterTest {

    public static void main(String[] args) {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            FileInputStream fis = new FileInputStream("hello.txt");
            FileOutputStream fos = new FileOutputStream("hello2.txt");

            isr = new InputStreamReader(fis, "utf-8");
            osw = new OutputStreamWriter(fos, "gbk");

            char[] buffer = new char[10];
            int len;
            while ((len = isr.read(buffer)) != -1){
                osw.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (isr != null){
                    isr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (osw != null){
                    osw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

}