InputStreamReader & OutputStreamWriter

1. code

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class IOTest {

    public static void main(String[] args) {

//        writeInfo();
        readInfo();
        

    }
    
    public static void readInfo(){
        String file = "d:\\a.txt";
        String charset = "utf-8";
        InputStreamReader reader = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            reader = new InputStreamReader(fis, charset);
            StringBuffer buffer = new StringBuffer();
            char[] buf = new char[64];
            int count = 0;
            while((count = reader.read(buf))!= -1){
                buffer.append(buf, 0, count);
            }
            System.out.println(buffer.toString());
            System.out.println();
//            System.getProperties().list(System.out);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void writeInfo(){
        String file = "d:\\a.txt";
        String charset = "utf-8";
        OutputStreamWriter writer = null;
        try {
            FileOutputStream fos = new FileOutputStream(file);
            writer = new OutputStreamWriter(fos, charset);
            writer.write("李四到此一游.....");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

2. 字节到字符 转换的桥梁 InputStreamReader & OutputStreamWriter

    避免乱码的方案就是 编解码规范一致

posted @ 2017-03-17 14:48  fangfan  阅读(174)  评论(0编辑  收藏  举报