天天看点

JavaSE 学习参考:字符流

JavaSE 学习参考:字符流

字符流是以字符(两个字节)为单位的流,Reader和Writer代表字符输入流和字符输出流,它们专为Java频繁的文字IO操作而设计的。常用方法列举如下:

Reader: 

int read(); 从流中读取一个字符

int reader(char[] buffer);读取若干可读字符至缓冲区,返回实际读取的字符个 数

Writer:

writer(int);将int型作为char类型字符输出到目标流中

writer(String);将字符串输出到目标流中。

writer(char[] buffer,int offset,int len);将字符缓冲区的字符从offset位置起共len个字符输出到目标流中

示例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();

}

}

}

}

}

继续阅读