本文目录:
Character Streams
Reader
Writer
write(char[] buf, int offset, int count)
Character Streams: character是16位的UTF-16字符, 基于文本的I/O流是人们可读的字符, 如程序的源代码. Charater streams被称为readers和writers. 对于多数的input或output streams都有相应的reader或writer字符流, 反之亦然. 和byte streams一样, character streams也要明确地关闭以释放资源.
java.io包中的Character Streams类型树:
Reader
public int read() throws IOException
作用: 读取一个字符.
说明: 返回值的取值范围为0-65535. 读取的数据作为int型数据的低16位. 若由于到达流的末尾而无字符可读, 则返回-1.
eg.
package mjn.io;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/**
* count the total characters
* and spaces of a text file
*
* @author MJN
* @date 2011-09-30
*/
public class CountSpaces {
public static void main(String[] args) throws IOException {
Reader in = new FileReader("in.txt");
int total = 0;
int spaces = 0;
int ch;
while ((ch = in.read()) != -1) {
if (Character.isWhitespace((char) ch)) {
spaces++;
}
total++;
}
System.out.println(total + " chars, " + spaces + " spaces.");
}
}
文件in.txt的内容:
hello world!
程序输出:
12 chars, 1 spaces.
public int read(char[] buf, int offset, int count) throws IOException
作用: 读取count个字符到数组buf(从buf[offset]到buf[offset + count - 1]), 返回实际读取的字符个数.
说明: 若因为其他原因(非遇到流的末尾)如流已被关闭, 则抛出IOException异常.
public int read(char[] buf) throws IOException
作用: 执行read(buf, 0, buf.length).
public int read(java.nio.CharBuffer buf) throws IOException
作用: 读取尽可能多的字符到buf中, 而不会有溢出.
public long skip(long count) throws IOException
作用: 跳过count个字符
public boolean ready() throws IOException
作用: 流是否已经准备好.
说明: 至少有一个字符可以读.
public abstract void close() throws IOException
作用: 关闭字符输入流.
Writer
public void write(int ch throws IOException
作用: 将一个字符写入流
说明: 只有ch的低16位被写入.
public void write(char[] buf, int offset, int count) throws IOException
作用: 将字符数组buf的count个字符写入流(从buf[offset]到buf[offset + count - 1]).
说明: 若count > buf.length - offset, 则抛出java.lang.IndexOutOfBoundsException异常.
public void write(char[] buf) throws IOException
作用: 执行write(buf, 0, buf.length).
public void write(String str, int offset, int count) throws IOException
作用: 将字符串str的count个字符写入流(从str.charAt(offset)到str.charAt(offset + count - 1)).
public void write(String str) throws IOException
作用: 执行write(str, 0, str.length()).
public abstract void flush() throws IOException
作用: 刷新缓冲.
public abstract void close() throws IOException
作用: 关闭流, 释放资源.
References:
[1] 《The Java Programming Language, Fourth Edition》