Java I/O 教程(八) Writer和Reader
Java Writer
Writer是一个用于写字符流的抽象类。其子类必须实现write(char[], int, int), flush(), 和 close()方法。
类定义
public abstract class Writer
extends Object
implements Appendable, Closeable, Flushable
属性
Modifier and Type Field Description
protected Object lock The object used to synchronize operations on this stream.
构造函数
protected Writer()Creates a new character-stream writer whose critical sections will synchronize on the writer itself.
常用方法
Writer append(char c) 往writer追加指定字符Writer append(CharSequence csq) 追加指定字符序列
Writer append(CharSequence csq, int start, int end) 追加指定字符序列的子序列
abstract void close() 先冲刷后关闭流
abstract void flush() 冲刷流
void write(char[] cbuf) 写字符数组
abstract void write(char[] cbuf, int off, int len) 写字符数组的部分
void write(int c) 写单个字符
void write(String str) 写字符串
void write(String str, int off, int len) 写部分字符串
例子
package com.dylan.io;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* @author xusucheng
* @create 2018-01-07
**/
public class WriterExample {
public static void main(String[] args) throws IOException {
Writer w = new FileWriter("D:\\output.txt");
String content = "I love my country.";
w.write(content);
w.close();
System.out.println("Done.");
}
}
Java Reader
Reader 是一个用于读取字符流的抽象类。其子类必须实现的方法只有:read(char[], int, int) 和 close()。
实现类包括: BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader
类定义
public abstract class Reader
extends Object
implements Readable, Closeable
属性
protected Object | lock
The object used to synchronize operations on this stream.
|
构造函数
protected | Reader()
Creates a new character-stream reader whose critical sections will synchronize on the reader itself.
|
protected | Reader(Object lock)
Creates a new character-stream reader whose critical sections will synchronize on the given object.
|
常用方法
abstract void | close()
Closes the stream and releases any system resources associated with it.
|
void | mark(int readAheadLimit)
Marks the present position in the stream.
|
boolean | markSupported()
Tells whether this stream supports the mark() operation.
|
int | read()
Reads a single character.
|
int | read(char[] cbuf)
Reads characters into an array.
|
abstract int | read(char[] cbuf, int off, int len)
Reads characters into a portion of an array.
|
int | read(CharBuffer target)
Attempts to read characters into the specified character buffer.
|
boolean | ready()
Tells whether this stream is ready to be read.
|
void | reset()
Resets the stream.
|
long | skip(long n)
Skips characters.
|
例子
package com.dylan.io;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/**
* @author xusucheng
* @create 2018-01-07
**/
public class ReaderExample {
public static void main(String[] args) throws IOException{
Reader r = new FileReader("D:\\output.txt");
int data = 0;
while ((data=r.read())!=-1){
System.out.print((char)data);
}
r.close();
}
}
下一章