(Byte stream and character stream) Write character output stream

Write character output stream

When the OutputStream byte output stream is used for data, all the data of the byte type is used. In many cases, the output of the string is more convenient. Therefore, the character output stream was introduced in JDK1.1: Writer:

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

 Main method:

  • Output string array: public void write​(char[] cbuf) throws IOException
  • Output string: public void write​(String str) throws IOException

Example: Use Write to output

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();
    }
}

Advantages: It can be done directly with character strings. Writer is a character stream, which can handle Chinese data conveniently.

Guess you like

Origin blog.csdn.net/weixin_46245201/article/details/112785275