“This is the sixth day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

The vast sea of thousands of thousands, thank you for this second you see here. Hope my article is helpful to you!

Wish you in the future, keep love, go to the mountains and seas!

Byte stream

After yesterday’s IO stream concept, we know that it can be a character stream and a byte stream, so today we will start with byte stream.

What about byte streams? It can be divided into byte output stream and byte input stream. Today we’re ready to take a closer look at byte output streams.

In the file world, everything is in bytes

We need to know that all file data (text, pictures, videos, etc.) are stored in the form of binary digits, byte by byte, so the transmission is the same. Thus, a byte stream can transfer arbitrary file data. When working with a stream, make it clear that whatever stream object is used, the underlying transmission is always binary.

Parent class of byte OutputStream (OutputStream)

OutputStream, which is the base class for all byte output streams, is a superclass of all classes representing byte output streams. The main function is to write the specified byte information to the destination. It sets some specifications and methods for the byte output stream of the whole system.

1. Take a look at his architecture

  • FileOutputStreamThe byte File output stream is used to write data to the File and from the program to other locations.
  • FilterOutputStream : Decorator mode is in the decorator, the specific decorator inherits from it, so the subclass of this class is used to decorate other streams, that is, the processing class.
  • ObjectOutputStream : is also a decorative class and is used for serialization. It mainly writes the original data type of Java object to the file to realize the persistent storage of the object.
  • BufferedInputStream: Buffer flow, yesFilterOutputStream The enhancement of decoration flow improves the efficiency of reading and writing.
  • PrintStreamIs:FilterOutputStream Enhancement of decorative flow. The ability to easily print values of various data types is a convenient way to output.
  • DataOutputStream: data output stream, which is used to decorate other output streams.

2. Methods in OutputStream

Subsequent subclasses have these methods, and the basic byte output stream needs to be written to the file with the write() method, and the resource is closed with the close() method.

3. FileOutputStream

1. Construction method
  • public FileOutputStream(File file): Creates a File output stream to write to the File represented by the specified File object.
  • public FileOutputStream(File file, boolean append): Similar to the above, with one more attribute, which will be discussed below
  • public FileOutputStream(String name): Creates a file output stream to write to the file with the specified name.
  • public FileOutputStream(String name, boolean append): Similar to the above, with one more attribute, which will be discussed below

This is the folder information before the constructor is created

public class IOTest {
    public static void main(String[] args) throws FileNotFoundException {
        //public FileOutputStream(File file)
        // Use the File object to create the stream object
        File file = new File("e:\\demo\\a.txt");
        FileOutputStream fos = new FileOutputStream(file);

        //public FileOutputStream(String name)
        // Create the stream object using the file name
        FileOutputStream fos2 = new FileOutputStream("E:\\demo\\b.txt"); }}Copy the code

We don’t have a.t_t, and b. t_t has content in it. Let’s see what happens when we execute the code:

As you can see, the console has no errors and no information. Let’s look at the folder information:

Note: When you create a stream object, you must pass in a file path. If this file does not exist in this directory, it will be created. If this file exists, it will be cleared.

So why is that? If I have a file that’s going to be wiped out, I don’t want to be wiped out every time I create an output stream object. How do I do that?

  • Let’s take a look at the constructor we call:

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

    As you can see, the constructor that contains the append property is called at the end, and append is false.

    And the append property means that if it’s true, it’s going to append the data, and if it’s false, it’s going to clear the data. This creates an output stream object that can specify whether or not to append. I added hello to B. TB first. And then we’re going to try and see if it’s cleared again

    public class AppendDemo {
        public static void main(String[] args) throws FileNotFoundException {
            FileOutputStream fos2 = new FileOutputStream("E:\\demo\\b.txt".true); }} The file is not empty.Copy the code

Consider that we did a few things when we created the byte output stream object, does that mean we didn’t create it directly? There are some steps at the bottom:

  1. Call the system function to create the file.
  2. createfosObject.
  3. thefosObject points to this file.
2. Write data

If we’re creating a byte output stream, it’s just to write data, otherwise what’s the use of creating it? Let’s see how to use it:

  1. Public void write(int b) : write one byte at a time.

    public class WriteTest {
        public static void main(String[] args) throws IOException {
            // Create an output stream object using the file name
            FileOutputStream fos = new FileOutputStream("E:\\demo\\a.txt");
    		
            //public void write(int b)
            fos.write(97);
    
            fos.close();
            // What happens if data is written after the stream is closed.
            //fos.write(98); //Exception in thread "main" java.io.IOException: Stream Closed}} After the execution result, check the file a.txt to obtain: ACopy the code

    A few points to note:

    • Be sure to close resources:

      In order to make the stream object garbage, so that it can be collected by the garbage collector.

      Notifies the system to release resources associated with the file.

    • Why write 97, and then write to the file to the character a:

      Because 97 represents the underlying binary data, go through that and find the corresponding character a in the character table. It’s also showing a instead of 97, but the underlying data is 97. Let’s look at the full ASCII code table:

    • If you shut down the stream resource, you cannot continue to operate on the stream. Otherwise, an IOException is reported.

    • Now when we do the I/O flow operation, except maybe the error will be printed on the console, everything else will be done directly in the file, and the result will be displayed directly in the file, and if you want to see the result, you open the file and see it.

  2. Public void write(byte[] b, int off, int len) : Each write is len bytes from the off index. This is equivalent to writing part of a byte array.

    public class WriteTest2 {
        public static void main(String[] args) throws IOException {
            // Create an output stream object using the file name
            FileOutputStream fos = new FileOutputStream("E:\\demo\\a.txt");
    
            //public void write(byte[] b)
            byte[] b = {97.98.99.100.101}; fos.write(b); fos.close(); }} After the execution result, check the a.txt file and obtain abcdeCopy the code
  3. Public void write(byte[] b) : write an array of bytes one at a time.

    public class WriteTest3 {
        public static void main(String[] args) throws IOException {
            // Create an output stream object using the file name
            FileOutputStream fos = new FileOutputStream("E:\\demo\\a.txt");
    
    
            //public void write(byte[] b, int off, int len)
            byte[] b = {97.98.99.100.101};
            fos.write(b,0.3); fos.close(); }} After the execution result, check the a.txt file and obtain ABCCopy the code
3. Implement line feeds

All of the above operations seem to be written on one line, so can we implement a newline?

Why don’t I see what the newline is first?

  • A carriage return\rAnd a newline\n
    • Return: return to the beginning of a line.
    • Newline: next line (newline).
  • Line feeds in the system:
    • On Windows, each line ends withCarriage return + line feed, i.e.,\r\n;
    • On Unix systems, each line ends with onlyA newline, i.e.,\n;
    • On the Mac, the end of each line isenter, i.e.,\r. Unified with Linux starting with Mac OS X.

We should be using Windows by default now, so we need to add \r\n. Let’s have a look at the code demo:

After executing the result, check the a.t_t file to get: epublicclass WriteTest4 {
    public static void main(String[] args) throws IOException {
        // Create an output stream object using the file name
        FileOutputStream fos = new FileOutputStream("E:\\demo\\a.txt");

        // Implement a newline after each character is written
        byte[] b = {97.98.99.100.101};
        for (byte bs : b) {
            fos.write(bs);
            // Write a newline, and write the newline as an array
            fos.write("\r\n".getBytes()); } fos.close(); }} After the command is executed, check the a.t_t file to obtain a b C d eCopy the code

Do you think it is difficult to look at the file every time, and then confirm whether added successfully? Next we’ll learn how to read a file from an input stream in a byte stream.

conclusion

I believe you have a certain understanding of IO stream byte output stream, looking forward to waiting for the next chapter of byte input stream teaching!

Of course, there are many streams waiting to watch together next time! Welcome to the next chapter!

So far, the world is closed for today, good night! Although this article is over, BUT I still, never finished. I will try to keep writing articles. The coming days are long, and the horse is slow!

Thank you for seeing this! May you be young and have no regrets!

Note: If there are any mistakes and suggestions, please leave a message! If this article is also helpful to you, I hope you give a lovely and kind attention, thank you very much!