java中的字符流--我的理解

来源:互联网 发布:hadoop源码编译 编辑:程序博客网 时间:2024/06/05 16:03

一、陈述

 字符流是处理字符的流,系统中字符的编码有多种,包括Unicode、UTF-8、UTF-16、GB2312、GBK等,不同的编码格式其所对应的字节是不同的,

其中java中字符采用的编码格式是Unicode编码,每个字符占两个字节。在中文Windows操作系统中的默认编码格式是GBK。

字符流在很大情况下主要是用来处理字符的编码转换文本文件的读取。

例如:

在对文本文件进行读写操作时,我们必须要清楚的知道我们所读取的文本文件的编码格式和我们要写入文本文件的编码格式,否则我们读取的文件信息

将会是乱码或错误的信息等,写入的信息也不利于以后该文件再读取。

 

二、字符流读写的代码实现:

读取:

InputStreamReader-------适配器----先取出该文本文件对应的字节流,然后按照该文本的编码格式(比如该文本文件的编码格式为utf-8)将字节流转换为字符流,

                                              最后在转换为java的JVM的编码格式(即unicode)

BufferedReader------------装饰器----为其他Reader提供缓冲区,在读取文本文件中我们主要使用该该类的readLine()函数,来每次读取一行。

 

写入操作:

OutputStreamWriter------适配器-----先使字符由Unicode码转化为我们要写入文本文件对应的编码格式(比如我们要写入文件的编码格式为utf-8),然后将该编码

                                            格式对应的字节流写入文本文件中

BufferedWriter-------------装饰器-----为其他Writer提供缓冲区,

PrintWriter------------------在写文本文件程序中,我们主要使用该类的格式化输出,以及该类型换行输入函数println()等。

 

实例程序如下:

package gyf.com;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;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.PrintWriter;import java.io.UnsupportedEncodingException;import java.nio.charset.Charset;public class Test1 {/** * @param args */public static void main(String[] args) throws IOException {// TODO Auto-generated method stubTest1 test1=new Test1();test1.copy("d:\\群硕工作.txt", null, "d:\\aa1.txt", "utf-8");}/////////////////拷贝函数public void copy(String filepathString,String encodeString,String toFilePathString,String encodString2){
File formFile=new File(filepathString);InputStreamReader iReader=null;BufferedReader bReader=null;File toFile=new File(toFilePathString);OutputStreamWriter oWriter=null;BufferedWriter bWriter=null;PrintWriter pWriter=null;try {if (encodeString!=null) {iReader=new InputStreamReader(new FileInputStream(formFile),encodeString);}else {iReader=new InputStreamReader(new FileInputStream(formFile));}bReader=new BufferedReader(iReader);if(encodString2!=null){oWriter=new OutputStreamWriter(new FileOutputStream(toFile),encodString2);    }else{oWriter=new OutputStreamWriter(new FileOutputStream(toFile),encodString2);    }bWriter=new BufferedWriter(oWriter);pWriter=new PrintWriter(bWriter);String string=bReader.readLine();while(string!=null){pWriter.println(string);System.out.println(string);;string=bReader.readLine();}} catch (UnsupportedEncodingException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (FileNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {bReader.close();pWriter.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}


 

 

 

原创粉丝点击