In the previous section, we learned how to construct a file byte output stream. In this section, we continue to learn how to use the output stream to write bytes and close the stream.
The purpose of the output stream is to provide a channel to the destination. The program can write data in the program to the destination through this channel. The file byte stream can call the write method inherited from the parent class to write files sequentially. The FileOutStream stream writes content to the file sequentially, that is, as long as the stream is not closed, each time the write method is called, content is written to the file sequentially until the stream is closed.
The write method of the byte output stream writes data to the destination in bytes.
The output stream calls this method to write a single byte to the destination.
The output stream calls this method to write a byte array to the destination.
Write len bytes from the given byte array starting at offset off to the destination.
Close the output stream.
Note : The FileOutputStream stream writes files sequentially. As long as the stream is not closed, content is sequentially written to the destination each time the write method is called until the stream is closed.
Before the operating system saves the bytes written by the program to the output stream to the disk, they are sometimes stored in the memory buffer. By calling the close() method , you can ensure that the operating system writes the contents of the stream buffer to it. The destination, that is, closing the output stream can flush the contents of the buffer used by the stream, usually to a disk file.
For example:
importjava.io.*;publicclassMain{publicstaticvoidmain(Stringargs[]){byte[]a=Happy New Year.getBytes();byte[]b=HappyNewYear.getBytes();Filefile=newFile(a.txt);//output The destination try{OutputStreamout=newFileOutputStream(file); //Point to the destination output stream System.out.println(file.getName()+size:+file.length()+bytes);out.write( a);//Write data to the destination out.close();out=newFileOutputStream(file,true);//Prepare to add content to the end of the file System.out.println(file.getName()+size:+file .length()+bytes);out.write(b,0,b.length);System.out.println(file.getName()+size:+file.length()+bytes);out. close();}catch(IOExceptione){System.out.println(Error+e);}}}
The running results are as follows:
Size of a.txt: 0 bytes Size of a.txt: 12 bytes Size of a.txt: 26 bytes