Original link Author: Jakob Jenkov Translator: Li Jing ([email protected])
FileOutputStream can write a byte stream to a file, which is a subclass of OutputStream, so you can use FileOutputStream as you would with OutputStream.
This is an example of a fileoutputstream:
01 |
OutputStream output = newFileOutputStream("c:\\data\\output-text.txt"); |
05 |
intdata = getMoreData(); |
Note that in order to be clear, the necessary exception handling is ignored. For more information about exception handling, refer to Java IO exception handling.
The write () method of FileOutputStream takes an int variable containing the bytes to be written (translator note: Low 8-bit data) as a parameter.
FileOutputStream also has other constructors that allow you to write files in different ways. Please refer to the official documentation for more information.
Overwrite of file content override vs Append appending
When you create a fileoutputstream that points to an existing file, you can choose to overwrite the entire file, or append the content to the end of the file. Different purposes can be achieved by using different constructors.
One of the constructors takes a filename as a parameter, overwriting any file that this file name points to.
1 |
OutputStream output = newFileOutputStream("c:\\data\\output-text.txt"); |
Another constructor takes 2 parameters: A file name and a Boolean value that indicates whether you need to overwrite the files. Here is an example of a constructor function:
1 |
OutputStream output = newFileOutputStream("c:\\data\\output-text.txt", true); //appends to file |
3 |
OutputStream output = newFileOutputStream("c:\\data\\output-text.txt", false); //overwrites file |
Write byte array
Since FileOutputStream is a subclass of OutputStream, you can also write byte arrays to FileOutputStream without having to write only one byte at a time. Refer to my OutputStream tutorial for more information on writing byte arrays.
Flush ()
When you write data to FileOutputStream, the data is likely to be cached in memory. At some later time, for example, only x data is writable each time, or FileOutputStream is closed, it is actually written to disk. When FileOutputStream is not closed and you want to make sure that the data written to FileOutputStream is written to disk, you can call the flush () method, This method guarantees that all data written to FileOutputStream will be written to disk.
original articles, reproduced please specify: reproduced from the Concurrent programming network –ifeve.com This article link address: Java io:fileoutputstream
Java Io:fileoutputstream