字符流是以字符(兩個(gè)字節(jié))為單位的流芥丧,Reader和Writer代表字符輸入流和字符輸出流,它們專為Java頻繁的文字IO操作而設(shè)計(jì)的坊罢。常用方法列舉如下:
int read();從流中讀取一個(gè)字符
int reader(char[] buffer);讀取若干可讀字符至緩沖區(qū)续担,返回實(shí)際讀取的字符個(gè) 數(shù)
writer(int);將int型作為char類型字符輸出到目標(biāo)流中
writer(String);將字符串輸出到目標(biāo)流中。
writer(char[] buffer,int offset,int len);將字符緩沖區(qū)的字符從offset位置起共len個(gè)字符輸出到目標(biāo)流中
示例1代碼:
public class TestWriter{
public static void main(String[] args) {
Writer writer = null;
try {
writer = new FileWriter("rw.txt");
writer.write('中');
writer.write("文漢字");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
示例2代碼:
public class TestReader{
public static void main(String[] args) {
Reader reader = null;
try {
reader = new FileReader("rw.txt");
int ch=-1;
while((ch=reader.read())!=-1){
System.out.print((char)ch);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}