Basic use of character output stream-writing a single character to a file

java.io.Writer: Character output stream, the topmost parent class of all character output streams, and an abstract class

共性的成员方法:
    void write(int c) 写入单个字符
    void write(char[] cbuf)写入单个字符数组
    abstract void write(char[] cbuf,int off,int len) 写入字符数组的某一部分,off数组的开始索引,len写入的字符个数
    void write(String str)写入字符串
    void write(String str,int off,int len) 写入字符串的某一部分,off字符串的开始索引,len写的字符个数
    void flush()刷新该流的缓冲
    void close()关闭此流,但要先刷新它

java.io.FileWriter extends OutputStreamWriter extends Writer
FileWriter: File character output stream
Function: write character data in memory to file

Construction method:

    FileWriter(File file)根据给定的File对象构造一个FileWriter对象
    FileWriter(String fileName)根据给定的文件名构造一个FileWriter对象
    参数:写入数据的目的地
        String fileName:文件的路径
        File file :是一个文件
     构造方法的作用:
        1.会创建一个FileWriter对象
        2.会根据构造方法中传递的文件/文件的路径,创建方法
        3.会把FileWriter对象指向差UN宫颈癌那好的文件

Use steps of character output (emphasis)

1.创建FileWriter对象,构造方法中绑定要写入数据的目的地
2.使用FileWriter中的方法write,把数据写入到内存缓冲区中(字符转换为字节的过程)
3.使用FileWriter中的方法flush,把内存缓冲区中的数据,刷新到文件中
4.释放资源(会先把内存缓冲区中的数据刷新到文件中)

【note】

  1. Although the parameter is four bytes of int type, only one character of information is written out.
  2. The close method is not called, the data is only saved to the buffer, not written out to the file

Code:

import java.io.FileReader;
import java.io.IOException;
public class Demo01Writer {
    
    
    public static void main(String[] args) throws IOException {
    
    
        // 1.创建FileWriter对象,构造方法中绑定要写入数据的目的地
        FileWriter fw = new FileWriter("day09_IOAndProperties\\d.txt");
        //2.使用FileWriter中的方法write,把数据写入到内存缓冲区中(字符转换为字节的过程)
        //void write(int c)写入单个字符
        fw.write(97);
        //3.使用FileWriter中的方法flush,把内存缓冲区中的数据,刷新到文件中
        fw.flush();
        //4.释放资源(会先把内存缓冲区中的数据刷新到文件中)
        fw.close();
    }
}

Program demonstration:
Insert picture description here
Insert picture description here

The difference between the flush() method and the close() method:
flush: flush the buffer, the stream object can continue to be used.
close: refresh the buffer first, and then notify the system to release resources. The stream object can no longer be used.
Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/108518580