Java CharArrayWriter writeTo()方法与示例
CharArrayWriter类writeTo()方法
writeTo()方法在java.io包中可用。
writeTo()方法用于将缓冲区数据写入给定的Writer流。
writeTo()方法是一种非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
writeTo()方法在写入缓冲区数据时可能会引发异常。
IOException:在获取任何输入/输出错误时,可能引发此异常。
语法:
public void writeTo(Writer w);
参数:
Writerw–表示要写入的流。
返回值:
该方法的返回类型为void,不返回任何内容。
示例
//Java程序演示示例
//CharArrayWriter的voidwriteTo(Writerw)方法
import java.io.*;
public class WriteToOfCAW {
public static void main(String[] args) {
CharArrayWriter caw_src = null;
CharArrayWriter caw_dest = null;
String s = "Java Programming";
try {
//实例化CharArrayWriter-
caw_src = new CharArrayWriter();
caw_dest = new CharArrayWriter();
//通过使用write()方法是
//将字符串写到流caw-
caw_src.write(s);
//通过使用toString()方法是
//将caw_src表示为字符串
System.out.print("caw_src: " + caw_src.toString());
System.out.println();
//通过使用writeTo()方法是
//将caw_src写入caw_dest-
caw_src.writeTo(caw_dest);
//通过使用toString()方法是
//将caw_dest表示为字符串
System.out.print("caw_dest: " + caw_dest.toString());
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
//释放与此相关的所有资源
//流
if (caw_src != null)
caw_src.close();
}
}
}输出结果
caw_src: Java Programming caw_dest: Java Programming