字节流与字符流4(Writer)

Writer在JDK1.1之后出现,其类定义如下:

public abstract class Writer
extends Object
implements Appendable, Closeable, Flushable
public interface Appendable{
   public Appendable append(char c);
   public Appendable append(CharSequence csq);
   public Appendable append(CharSequence csq,int start,int end);
}

在Appendable接口里面定义了追加的操作,而且追加的数据都是字符或者字符串。

在Writer类里面定义有以下输出方法(部分):

输出全部字符数组:public void write(char[] chnf)
输出字符串:public void write(String str);

Writer同样是一个抽象类,要想实例化,应该使用FileWriter子类。

范例:使用Writer类进行内容输出

    public static void main(String[] args) throws Exception{
        //1.定义要输出的文件目录
        File file=new File("e:"+File.separator+"demo"+File.separator+"my.txt");
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();//如果文件不存在,创建文件
        }
        //2.实例化Writer子类对象
        Writer out=new FileWriter(file);
        //3.进行内容输出
        String str="Hello sl";
        out.write(str);
        out.close();
    }   

可以发现Writer作为字符输出流,可以直接进行字符串的输出,这一点就比OutPutStream强了。

猜你喜欢

转载自blog.csdn.net/weixin_33843409/article/details/87040372
今日推荐