Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to a file and save it dynamically in java

Tags:

java

java-io

I have a requirenment to write to a file rather than in System.out.println and save it at same time so that user can see the progress anytime by opening the file.

Right now I am using following code

     FileWriter fstream = null;
        File file1 = new File(logFile);
        fstream = new FileWriter(file1);
        out = new BufferedWriter(fstream);
               out.write(msg);
     out.write("\n");

but it does not save the contents to the file unless I say Out.close();

FYI - 1. This is a Java EE application code. 2. I donot want to user Log4jLogger

Is there any simpler way to do this? Any pointers?

like image 315
user837593 Avatar asked Dec 05 '25 20:12

user837593


1 Answers

You don't need to call close() - just call flush().

Flushes this output stream and forces any buffered output bytes to be written out.

like image 117
Amir Afghani Avatar answered Dec 08 '25 10:12

Amir Afghani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!