(字节流与字符流)Write字符输出流

Write字符输出流

使用OutputStream字节输出流进行数据的时候使用的都是字节类型的数据,而很多的情况下字符串的输出是比较方便的,所以在JDK1.1的时候又推出了字符输出流:Writer:

public abstract class Writer extends Object implements Appendable, Closeable, Flushable

 主要方法:

  • 输出字符串数组:public void write​(char[] cbuf) throws IOException
  • 输出字符串:public void write​(String str) throws IOException

范例:使用Write输出

package 字节流与字符流;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class Writer字符流输出 {
    public static void main(String[] args) throws IOException {
        File file = new File("F:"+File.separator+"Test"+File.separator+"test.txt");
        if(file.getParentFile().exists()){  //没有父路径
            file.getParentFile().mkdirs();  //创建一个父路径
        }
        Writer writer = new FileWriter(file,true);  //实例化File,要求每次执行内容被覆盖可以将true去掉
        writer.write("加入的内容");
        writer.append("我是追加的");
        writer.close();
    }
}

优势:可以直接利用字符串完成,Writer是字符流,可以方便处理中文数据。

猜你喜欢

转载自blog.csdn.net/weixin_46245201/article/details/112785275
今日推荐