字符流

字节流提供了处理任何类型输入/输出操作的功能(对于计算机而言,一切都是0 和1,只需把数据以字节形式表示就够了),但它们不可以直接操作Unicode字符,一个Unicode字符占用2个字节,而字节流 一次只能操作一个字节。既然Java的一个主要目的是支持“ 只写一次,到处运行” 的哲学,包括直接的字符输入/输出支持是必要的。字符流层次结构的顶层是Reader 和Writer 抽象类。

• 由于Java采用16位的Unicode字符,因此需要基于字符的输入/输出操作。从Java1.1版开始,加入了专门处理字符流的抽象类Reader和Writer,前者用于处理输入,后者用于处理输出。这两个类类似于InputStream和OuputStream,也只是提供一些用于字符流的规定,本身不能用来生成对象。

字节流一次处理一个字节,字符流一次处理一个字符。

• Java程序语言使用Unicode来表示字符串和字符,Unicode使用两个字节来表示一个字符,即一个字符占16位

Reader
Reader是定义Java的字符输入流的抽象类,该类的所有方法在出错的情况下都将引发IOException。Reader类中有这些方法:

/**
* Abstract class for reading character streams. The only methods that a
* subclass must implement are read(char[], int, int) and close(). Most
* subclasses, however, will override some of the methods defined here in order
* to provide higher efficiency, additional functionality, or both.*/
public abstract class Reader implements Readable, Closeable {/**
* Attempts to read characters into the specified character buffer.
* The buffer is used as a repository of characters as-is: the only
* changes made are the results of a put operation. No flipping or
* rewinding of the buffer is performed.*/
public int read(java.nio.CharBuffer target) throws IOException {
}
/**
* Reads a single character. This method will block until a character is
* available, an I/O error occurs, or the end of the stream is reached.*/
public int read() throws IOException {
}
/**
* Reads characters into an array. This method will block until some input
* is available, an I/O error occurs, or the end of the stream is reached.*/
public int read(char cbuf[]) throws IOException {
return read(cbuf, 0, cbuf.length);
}
/**
* Reads characters into a portion of an array. This method will block
* until some input is available, an I/O error occurs, or the end of the
* stream is reached.*/
abstract public int read(char cbuf[], int off, int len) throws IOException;/**
* Skips characters. This method will block until some characters are
* available, an I/O error occurs, or the end of the stream is reached.*/
public long skip(long n) throws IOException {
}
/**
* Tells whether this stream is ready to be read.*/
public boolean ready() throws IOException {
}/**
* Closes the stream and releases any system resources associated with
* it. Once the stream has been closed, further read(), ready(),
* mark(), reset(), or skip() invocations will throw an IOException.
* Closing a previously closed stream has no effect.*/
abstract public void close() throws IOException;
}

Writer
Writer是定义字符输出流的抽象类,所有该类的方法都返回一个void值并在出错的条件下引发IOException。Writer类中的方法有:

/**
* Abstract class for writing to character streams. The only methods that a
* subclass must implement are write(char[], int, int), flush(), and close().
* Most subclasses, however, will override some of the methods defined here in
* order to provide higher efficiency, additional functionality, or both.*/
public abstract class Writer implements Appendable, Closeable, Flushable {/**
* Writes a single character. The character to be written is contained in
* the 16 low-order bits of the given integer value; the 16 high-order bits
* are ignored.*/
public void write(int c) throws IOException {
}
/**
* Writes an array of characters.*/
public void write(char cbuf[]) throws IOException {
write(cbuf, 0, cbuf.length);
} /**
* Writes a portion of an array of characters.*/
abstract public void write(char cbuf[], int off, int len) throws IOException; /**
* Writes a string.*/
public void write(String str) throws IOException {
write(str, 0, str.length());
} /**
* Writes a portion of a string.*/
public void write(String str, int off, int len) throws IOException {
}
/**
* Appends the specified character sequence to this writer.*/
public Writer append(CharSequence csq) throws IOException {
} /**
* Appends a subsequence of the specified character sequence to this writer.*/
public Writer append(CharSequence csq, int start, int end) throws IOException {
} /**
* Appends the specified character to this writer.*/
public Writer append(char c) throws IOException {
} /**
* Flushes the stream. If the stream has saved any characters from the
* various write() methods in a buffer, write them immediately to their
* intended destination. Then, if that destination is another character or
* byte stream, flush it. Thus one flush() invocation will flush all the
* buffers in a chain of Writers and OutputStreams.*/
abstract public void flush() throws IOException; /**
* Closes the stream, flushing it first. Once the stream has been closed,
* further write() or flush() invocations will cause an IOException to be
* thrown. Closing a previously closed stream has no effect.*/
abstract public void close() throws IOException; }

InputStreamReader和OutputStreamWriter类

• 这是java.io包中用于处理字符流的基本类,用来在字节流和字符流之间搭一座“桥”。这里字节流的编码规范与具体的平台有关,可以在构造流对象时指定规范,也可以使用当前平台的缺省规范

An InputStreamReader is a bridge from byte streams to character streams: It
reads bytes and decodes them into characters using a specified
java.nio.charset.Charset 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.
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.

• InputStreamReader和OutputStreamWriter类的主要构造方法如下
– public InputSteamReader(InputSteam in)
– public InputSteamReader(InputSteamin,String enc)
– public OutputStreamWriter(OutputStream out)
– public OutputStreamWriter(OutputStream out,String enc)

• 其中in和out分别为输入和输出字节流对象,enc为指定的编码规范(若无此参数,表示使用当前平台的缺省规范,可用getEncoding()方法得到当前字符流所用
的编码方式)。
• 读写字符的方法read()、 write(),关闭流的方法close()等与Reader和Writer类的同名方法用法都是类似的。

public class StreamTest {
public static void main(String[] args) throws Exception { //字节流
FileOutputStream fos = new FileOutputStream("file.txt"); //变成字符流
OutputStreamWriter osw = new OutputStreamWriter(fos); //加上缓冲功能
BufferedWriter bw = new BufferedWriter(osw); bw.write("http://www.google.com");
bw.write("\n");
bw.write("http://www.baidu.com"); bw.close(); FileInputStream fis = new FileInputStream("file.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr); String str = br.readLine(); while (null != str) {
System.out.println(str); str = br.readLine();
} br.close(); }
}

读取键盘输入

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

FileReader和FileWriter

• FileReader类创建了一个可以读取文件内容的Reader类。 FileReader继承于InputStreamReader。 它最常用的构造方法显示如下
– FileReader(String filePath)
– FileReader(File fileObj)
– 每一个都能引发一个FileNotFoundException异常。这里, filePath是一个文件的完整路径,fileObj是描述该文件的File 对象

public class FileReader1 {
public static void main(String[] args) throws Exception {
File file = new File("c:\\CharSet.java");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String str;
while (null != (str = br.readLine())) {
System.out.println(str);
}
br.close();
}
}

• FileWriter 创建一个可以写文件的Writer类。 FileWriter继承于OutputStreamWriter.它最常用的构造方法如下:
– FileWriter(String filePath)
– FileWriter(String filePath, boolean append)
– FileWriter(File fileObj)
– append :如果为 true,则将字节写入文件末尾处,而不是写入文件开始处

• 它们可以引发IOException或SecurityException异常。这里, filePath是文件的完全路径, fileObj是描述该文件的File对象。如果append为true,输出是附加到文件尾的。
• FileWriter类的创建不依赖于文件存在与否。在创建文件之前, FileWriter将在创建对象时打开它来作为输出。如果你试图打开一个只读文件,将引发一个IOException异常

public class FileWriter1 {
public static void main(String[] args) throws IOException {
String str = "hello world welcome nihao hehe"; char[] buffer = new char[str.length()]; str.getChars(0, str.length(), buffer, 0); FileWriter f = new FileWriter("file2.txt"); for (int i = 0; i < buffer.length; i++) {
f.write(buffer[i]);
} f.close();
}
}

Java IO3:字符流的更多相关文章

  1. Java Io 字符流

    Java Io 字符流包含: 1. InputStreamReader  它是由byte流解析为char流,并且按照给定的编码解析. 2. OutputStreamWrite  它是char流到byt ...

  2. 理解Java中字符流与字节流

    1. 什么是流 Java中的流是对字节序列的抽象,我们可以想象有一个水管,只不过现在流动在水管中的不再是水,而是字节序列.和水流一样,Java中的流也具有一个"流动的方向",通常可 ...

  3. 理解Java中字符流与字节流的区别(转)

    1. 什么是流 Java中的流是对字节序列的抽象,我们可以想象有一个水管,只不过现在流动在水管中的不再是水,而是字节序列.和水流一样,Java中的流也具有一个“流动的方向”,通常可以从中读入一个字节序 ...

  4. Java IO: 字符流的Buffered和Filter

    作者: Jakob Jenkov  译者: 李璟(jlee381344197@gmail.com) 本章节将简要介绍缓冲与过滤相关的reader和writer,主要涉及BufferedReader.B ...

  5. Java IO: 字符流的Piped和CharArray

    作者: Jakob Jenkov 译者: 李璟(jlee381344197@gmail.com) 本章节将简要介绍管道与字符数组相关的reader和writer,主要涉及PipedReader.Pip ...

  6. 理解Java中字符流与字节流的区别

    1. 什么是流 Java中的流是对字节序列的抽象,我们可以想象有一个水管,只不过现在流动在水管中的不再是水,而是字节序列.和水流一样,Java中的流也具有一个“流动的方向”,通常可以从中读入一个字节序 ...

  7. Java中字符流与字节流的区别

    字符流处理的单元为2个字节的Unicode字符,分别操作字符.字符数组或字符串,而字节流处理单元为1个字节,操作字节和字节数组.所以字符流是由Java虚拟机将字节转化为2个字节的Unicode字符为单 ...

  8. Java:文件字符流和字节流的输入和输出

    最近在学习Java,所以就总结一篇文件字节流和字符流的输入和输出. 总的来说,IO流分类如下: 输入输出方向:     输入流(从外设读取到内存)和输出流(从内存输出到外设) 数据的操作方式: 字节流 ...

  9. Java之字符流操作-复制文件

    package test_demo.fileoper; import java.io.*; /* * 字符输入输出流操作,复制文件 * 使用缓冲流扩展,逐行复制 * */ public class F ...

  10. Java之字符流读写文件、文件的拷贝

    字符流读数据 – 按单个字符读取 创建字符流读文件对象: Reader reader = new FileReader("readme.txt"); 调用方法读取数据: int d ...

随机推荐

  1. Alluxio1.0.1最新版(Tachyon为其前身)介绍,+HDFS分布式环境搭建

    Alluxio(之前名为Tachyon)是世界上第一个以内存为中心的虚拟的分布式存储系统.它统一了数据访问的方式,为上层计算框架和底层存储系统构建了桥梁. 应用只需要连接Alluxio即可访问存储在底 ...

  2. C#委托的异步调用1

    本文将主要通过“同步调用”.“异步调用”.“异步回调”三个示例来讲解在用委托执行同一个“加法类”的时候的的区别和利弊. 首先,通过代码定义一个委托和下面三个示例将要调用的方法: /*添加的命名空间 u ...

  3. Mac下使用Web服务器性能/压力测试工具webbench、ab、siege

    Web开发,少不了的就是压力测试,它是评估一个产品是否合格上线的基本标准,下面我们来一一剖析他们的使用方式. 测试前,前面先把系统的端口限制数改大,看看Mac下面的默认限制 ulimit -a ope ...

  4. 彻底删除sql server的方法

    请先确定是否把sql相关的东西删了,建议进行如下操作. 1.先下个Windows Install Clean Up,清理sql相关东西,要全部清理. 2.到控制面板--添加删除程序中看是否还有未删的. ...

  5. 打破常规——大胆尝试在路由器上搭建SVN服务器

    注册博客园挺久了,一直比较懒,虽然有几次想写点文章,但是一直没有行动,今天给大家带来一篇比较有意思的文章,不涉及技术上的,希望大家轻拍.本文的文字和图片全部为原创,尊重作者转载请注明出处! 说起路由器 ...

  6. Python学习_从文件读取数据和保存数据

    运用Python中的内置函数open()与文件进行交互 在HeadFirstPython网站中下载所有文件,解压后以chapter 3中的“sketch.txt”为例: 新建IDLE会话,首先导入os ...

  7. python编程语言缩进格式

    python的缩进格式是python语法中最特别的一点,很多已经习惯了其他语言的朋友再去学python的话,开始会觉的不太 习惯. 怎么看怎么都觉的别扭,也有一些朋友因为这个特别的格式与python失 ...

  8. 巧用system函数个性化屏幕显示

    函数名:system 功  能: 发出一个DOS命令 用  法: system("DOS命令");             (system函数需加头文件<stdlib.h&g ...

  9. 九、mysql触发器的概念

    .所谓触发器,就是指设置好某个表的某个操作(insert ,update ,delete)时候,同时触发的一个操作: 一般用来,比如说删除文章主栏目,那么可以利用触发器删除这个文章栏目下的所有文章 . ...

  10. Microsoft Office Excel 不能访问文件

    问题描述: Microsoft Office Excel 不能访问文件“XX.xls”.可能的原因有: 1 文件名称或路径不存在.2 文件正被其他程序使用.3 您正要保存的工作簿与当前打开的工作簿同名 ...