Byte output stream [OutputStream]

Byte output stream writes data to file

java.io.OutputStream:Byte output stream
This abstract class is the superclass of all classes that represent output byte streams.

定义了一些子类共性的成员方法:
    public void close() : 关闭输出流并释放与此流相关联的任何系统资源
    public void flush() : 刷新输出流并强制任何缓冲的输出字节被写出
    public void write(byte[] b) : 将 b.length字节从指定的字节数组写入次输出流
    public void write(byte[] b,int off,int len) : 从指定的字节数组写入len字节,从偏移量off开始输出到此输出流
    public abstract void write(int b) : 将指定的字节输出流

java.io.FileOutputStream extends OutputStream
FileOutputStream:文件字节输出流
作用:把内存中的数据写入到硬盘的文件中

构造方法:
    FileOutputStream(String name)创建一个向具有指定名称的文件中写入数据的输出文件流
    FileOutputStream(File file)创建一个向指定File对象表示的文件中写入数据的文件输出流
    参数:写入数据的目的
        String name:目的地是一个文件的路径
        File file :目的地是一个文件
    构造方法的作用:
        1.创建一个FileOutputStream对象
        2.会根据构造方法中传递的文件/文件路径,创建一个空的文件
        3.会把FileOutputStream对象指向创建好的文件

The principle of writing data (memory -> hard disk)
java program -> JVM (java virtual machine) -> OS (operating system) -> OS calls the method of writing data -> writing data to a file

Steps to use byte output stream (emphasis)
1. Create a FileOutputStream object, and pass the destination of the written data in the construction method
2. Call the method write in the FileOutputStream object to write the data to the file
3. Release resources (stream Use will occupy a certain amount of memory, and the memory must be cleared after use to improve the efficiency of the program)

Code:

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo01OutputStream {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //1.创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
        FileOutputStream fos = new FileOutputStream("day09_IOAndProperties\\a.txt");
        //2.调用FileOutputStream对象中的方法write,把数据写入到文件中
        //public abstract void write(int b) : 将指定的字节输出流
        fos.write(78);
        //3.释放资源(刘使用会占用一定的内存,使用完毕要把内存清空,提供程序的效率)
        fos.close();
    }
}

Program demonstration:
Insert picture description here
Insert picture description here

Guess you like

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