不管是磁盘还是网络传输,最小的存储单元都是字节,而不是字符,所以 I/O 操作的都是字节而不是字符,但是为啥有操作字符的 I/O 接口呢?这是因为我们的程序中通常操作的数据都是以字符形式,有时我们必须把来自于"字节"层次结构中的类和“字符”层次结构中的类结合起来使用,为了实现这个目的,要用到"适配器"类:InputStreamReader可以把InputStream转化为Reader,而OutputStreamWriter可以把OutputStream转化为Writer。接着上一篇文章,本篇文章讲述同步并阻塞式线程的第二类,基于字符的Writer和Reader。
Writer相关类层次结构:
Reader相关类层次结构:
具体代码示例如下:
package io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.CharArrayReader; import java.io.CharArrayWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; public class ReaderandWriter { public static void main(String[] args) { /** * FileWriter与FileReader */ try { FileWriter fw = new FileWriter("file.txt"); String str = "大家好!"; fw.write(str); fw.close(); FileReader fr = new FileReader("file.txt"); int ch = 0; while((ch = fr.read()) != -1){ System.out.print((char)ch); } fr.close(); } catch (IOException e) { e.printStackTrace(); } /** * BufferedWriter与BufferedReader */ try { BufferedWriter bw = new BufferedWriter( new FileWriter("file.txt")); String str = "你好!"; bw.write(str); bw.close(); BufferedReader br = new BufferedReader(new FileReader("file.txt")); System.out.println(br.readLine()); br.close(); } catch (IOException e) { e.printStackTrace(); } /** * StringWriter与StringReader */ try{ String str = "今天很美好,明天很美好,后天还是很美好..."; StringReader sr = new StringReader(str); String strRead = null; char[] size = new char[1024]; while((sr.read(size)) != -1){ strRead = new String(size); } sr.close(); StringWriter sw = new StringWriter(); sw.write(strRead); sw.close(); System.out.println(sw.toString()); }catch(Exception e){ e.printStackTrace(); } /** * PrintWriter */ try { PrintWriter pw = new PrintWriter(new FileWriter("file.txt")); pw.append("你们好!"); pw.close(); BufferedReader br = new BufferedReader(new FileReader("file.txt")); System.out.println(br.readLine()); br.close(); } catch (IOException e) { e.printStackTrace(); } /** * CahrArrayWriter与CharArrayReader */ try { CharArrayWriter caw = new CharArrayWriter(); String str = "我们都有一个家!"; caw.write(str); caw.close(); System.out.println(caw.toString()); char[] chars = {'A','B','C','D','E'}; CharArrayReader car = new CharArrayReader(chars); int len = 0; while((len = car.read()) != -1){ System.out.print((char)len); } car.close(); } catch (IOException e) { e.printStackTrace(); } } }
图片来自:http://www.ibm.com/developerworks/cn/java/j-lo-javaio/
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-09 20:19:29