从OutStreamWriter 和Filewriter谈Java编码

首先看JAVA API的描述:

ABOUT OutputStreamWriter:

"An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted."

「OutputStreamWriter是连接字符流和字节流的桥梁:写入这个类的字符流会被编码为“charset”所指示的编码格式。这个charset可以通过名字指定或是直接给出,也接受平台的默认charset(好像是UTF-8)。」

ABOUT FileWriter:

"The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable."

「这个类的构造函数假定用户使用默认的编码方式,并且允许使用默认的字节缓冲大小。」

 

另外FileWriter是OutputStreamWriter的子类。FileWriter只能使用默认的编码UTF-8,这造成输出中文的时候会出现乱码。而OutputStreamWriter可以避免这一点。

 

使用:

OutputStreamWriter(OutputStream out, Charset cs)
Creates an OutputStreamWriter that uses the given
charset.

当然还有其他参数的OutputStreamWriter类,在API中有列举。

于是可以写成:

OutputStreamWriter ow = new OutputStreamWriter(os,Charset.forName("unicode"));

其中os是OutputStream类的实例。但是Eclipse会提示OutputStream是不能直接实例化的,这时可以通过FileOutputStream向上转型(关于对象的转型)来得到:

OutputStream os = null ; 
os = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/Android/ContactME.txt");

以上。

 

参考:http://zhidao.baidu.com/question/918312230716365579.html?quesup2&oldq=1

posted @ 2014-02-28 12:43  LarryLawrence  阅读(2650)  评论(0编辑  收藏  举报