“This is the 9th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Recently, the project encountered the functional requirements of generating user authentication information according to the data, which happened to use FileOutputStream output stream object. Here we learn and summarize the operation process of using FileOutputStream output byte stream to file.

1. Class structure definition

The FileOutputStream class is used in Java for byte stream output (writing to files), as opposed to the FileWriter class for character stream output.

The FileOutputStream class inheritance diagram can be expressed as:

  • The FileOutputStream class inherits from the OutputStream class
  • OutputStream, as an abstract class, is the superclass of all byte output classes and implements the Flushable and Closeable interfaces
  • The Flushable interface is used to provide the flush() flushing method
  • The Closeable interface is used to provide the close() closure method

2. Constructor

The FileOutputStream class defines multiple constructors for different arguments.

2.1 Create an output stream based on File

Since you are writing the byte stream to a specified file, you first need to create an object corresponding to the file in the Java language and take the file object as a parameter to generate a byte output stream object.

// Specify the File File object to create the output stream
public FileOutputStream(File file) throws FileNotFoundException{}// Specify the File object to create the output stream and set whether the output is appended
//append=false overwrites the file content
public FileOutputStream(File file, boolean append) public FileOutputStream(File file, boolean append){}Copy the code

2.2 Create an output stream based on the string path

The output stream object can be created using a string directly to specify the path information for the output file.

// Specifies the file string to create the output stream
public FileOutputStream(String name) throws FileNotFoundException {}// Specify file path string to create output stream and set output to file in append mode,
//append=false overwrites the file content
public FileOutputStream(String name, boolean append) throws FileNotFoundException {}Copy the code

When you create an output stream object using String as an argument, you essentially create a FileOutputStream object using a File object, except that the String value is generated as a File object inside the constructor.

public FileOutputStream(String name) throws FileNotFoundException {
    this(name ! =null ? new File(name) : null.false);
}
Copy the code

2.3 Precautions for Creating Output Streams

When initializing a FileOutputStream object from the constructor, note the following:

  • If the specified file does not exist, a new FileOutputStream object is created for the specified file
  • If it cannot be created, a FileNotFoundException is thrown
    • The directory does not exist. For example, the /opt/local/file. TXT directory does not exist on Windows, the directory cannot be created
    • If a folder with the specified file name exists, the creation fails
    • The file path string is invalid, for example, /opt’/loca’/file. TXT

3. Output the byte stream to the file

Once the FileOutputStream object is created, you can output the byte stream to the specified file using the method provided in the object. The write() method provided in the object writes the byte content to the file summary. IOException must be thrown when calling the method output.

3.1 the write () method

FileOutputStream’s write(int b) method receives an int because, as a byte stream output, it internally calls a local write method that converts int arguments to the corresponding ASCALL code or GBK code.

// Write method Private Native void Write (int B, Boolean append) throws IOException; // Invoking the local write method Public void write(int b) throws IOException {write(b, append); }Copy the code

3.2 writeBytes () method

In addition to the write() method receiving a byte, the writeBytes() method is provided to receive an array of bytes.

// Native methods
private native void writeBytes(byte b[], int off, int len, boolean append) throws IOException;

// The write method of the object, which internally calls the local method
public void write(byte b[]) throws IOException {
    writeBytes(b, 0, b.length, append);
}

// Provide offset and length parameters, optionally output the contents of the byte array to the file
public void write(byte b[], int off, int len) throws IOException {
    writeBytes(b, off, len, append);
}
Copy the code
  • The writeBytes() method takes a byte array as an argument so that strings in Java, etc., can be written to a file through the byte array.
  • "Hello FileOutputStream!" .getBytes()You can get an array of bytes corresponding to a string.
  • When writing a byte array, the writeBytes(byte b[]) method combines consecutive bytes into corresponding contents and writes them to a file.

3.3 Closing the Output Stream

The.close() method is called to close the stream when the stream object is finished, freeing up the resources it occupies.

4. Complete the process

The FileOutputStream object is relatively simple to use and has the following flow:

  1. Define the file address,
  2. Create a file object based on the file address (optional),
  3. Passing in file information creates an output stream object FileOutputStream,
  4. Gets an array of bytes corresponding to what was written,
  5. Call the write method of the output stream object, pass the byte array argument, write the contents to a file,
  6. Close the output stream.
public static void main(String[] args) throws IOException {
    String path = "D:\\ProjectTest\\WorkSpace\\file\\test.txt";
    
    //File file = new File(path);
    //FileOutputStream fileOutputStream = new FileOutputStream(file);
    
    FileOutputStream fileOutputStream = new FileOutputStream(path);

    byte[] bytes = "Hello FileOutputStream!".getBytes();
    
    fileOutputStream.write(bytes);
    
    fileOutputStream.close();
}
Copy the code