字符流ReaderWriter,字符转换流 OutputStreamWriterInputStreamReader
Posted 征程
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符流ReaderWriter,字符转换流 OutputStreamWriterInputStreamReader相关的知识,希望对你有一定的参考价值。
Reader、Writer是所有字符流的超类。
Writer类方法
void write(String str)
void write(char[] cbuf, int off, int len);
void flush()
void close
OutputStreamWriter构造方法字符编码默认为系统编码,可以不写
FileWriter的append默认为false,可以不写。另一个构造(File file, boolean append)
Writer out = new FileWriter("E:/a.txt", true); OutputStream ops = new FileOutputStream("E:/a.txt", true); Writer out = new OutputStreamWriter(ops, "GBK"); // 默认系统编码,可以不写
Reader类
int read(char[] cbuf)
InputStreamReader与OutputStreamWriter类似
FileReader 与 FileWriter类似’
Reader in = new FileReader("E:/gbk.txt"); InputStream inStream = new FileInputStream("E/gbk.txt"); Reader in = new InputStreamReader(inStream, "gbk");
BufferedReader,BufferedWriter使用与BufferedOutputStream, BufferedInputStream用法相同
这段代码对比了4种方式进行字符流复制速度。
public static void main(String[] args) throws IOException, InterruptedException { /*文件 114M * 逐字符读,无缓冲 10252 * 逐字符读,有缓冲 7730 * 1024字符,无缓冲 3645 * 1024字符 有缓冲 3578 */ long b = System.currentTimeMillis(); copy_4(); long a = System.currentTimeMillis(); System.out.println(a-b); } public static void copy_1() throws IOException{ Reader r = new FileReader("E:/test.pdf"); BufferedReader in = new BufferedReader(r); Writer w = new FileWriter("E:/copy.pdf"); BufferedWriter out = new BufferedWriter(w); int len; while((len = in.read()) != -1) { out.write(len); } in.close(); out.close(); } public static void copy_2() throws IOException{ Reader in = new FileReader("E:/test.pdf"); Writer out = new FileWriter("E:/copy.pdf"); int len; while((len = in.read()) != -1) { out.write(len); } in.close(); out.close(); } public static void copy_3() throws IOException{ Reader in = new FileReader("E:/test.pdf"); Writer out = new FileWriter("E:/copy.pdf"); int len; char[] cbuf = new char[1024]; while((len = in.read(cbuf)) != -1) { out.write(cbuf,0,len); out.flush(); } in.close(); out.close(); } public static void copy_4() throws IOException{ Reader r = new FileReader("E:/test.pdf"); BufferedReader in = new BufferedReader(r); Writer w = new FileWriter("E:/copy.pdf"); BufferedWriter out = new BufferedWriter(w); int len; char[] cbuf = new char[1024]; while((len = in.read(cbuf)) != -1) { out.write(cbuf,0,len); out.flush(); } in.close(); out.close(); }
以上是关于字符流ReaderWriter,字符转换流 OutputStreamWriterInputStreamReader的主要内容,如果未能解决你的问题,请参考以下文章