The answer to the need for a flash in input / output streams in java in a file stream

Hey. I need an answer to the need for a flash in the input / output streams in java.since, in my program with a flash and without a flash the output is the same .ie, every thing is written to the destination file. Then why do I need flush? will the input stream consume buffer memory?

below is my simple sample program

file = new File("c:/newfile.txt"); fop = new FileOutputStream("c:/newfile.txt"); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); 

even when I run the command and close it, can I write the contents to the file correctly ..? then do we need flush? and will the output stream consume memory?

+4
source share
2 answers

Close call streams in the stream, so no flash is needed to close the stream.

A flash is useful if you want to make sure that the data is saved without closing the stream, for example. when sending messages over the Internet or when recording to the console. You may notice that if you write to the console using system.out.print (), the output is not displayed until you name the flash, or until a new line appears in the text (in this case, Java will call the flash for you) .

More on this question

+1
source

In fact, FileOutputStream not buffered, so the data is written directly to the file.

The abstract OutputStream defines a flush (empty method) to accommodate the needs of buffered streams as well, so FileOutputStream inherits it.

If you are unsure of the underlying implementation, it is generally recommended that you delete threads before closing them.

In addition, there is a small error in your code:

  file = new File("c:/newfile.txt"); fop = new FileOutputStream("c:/newfile.txt"); // Will never happen, new FileOutputStream creates the file if (!file.exists()) { file.createNewFile(); } 

EDIT:

Regarding the close part of the question:

When you comment out close() , the completion of main() the close method is called by the finalizer (i.e. before the thread gets garbage collected, the JVM thread calls its finalize() method, which in turn calls close() ) but you cannot reasonably rely on the finalizer: you do not own it, and you cannot be sure of its activation.

Again, it's best to call close() explicitly.

0
source

All Articles