Java: Writing to a log file from a server -


I am trying to create a small chat room log file yet it is for logging for me:

  Fixed zero log (strings) {try {buffed author authors = new buffed waist (new filename ("log" + getting "+". "text")); writer.write (s); } Hold (IOException e) {e.printStackTrace (); }}   

Every time I broadcast to the cloud, I call it in a thread like this:

  log (name + " String ")   

But after that it is called and does not release the program. However, when it used to work, only one thing in the text file is a row, which was previously called. How can these two worms cure?

As stated in the other answer, you do not close the file and you do not write a line separator Are there.

I know that there is a right answer in Java 7, but you said in the comment that you can not use it. (I think you are using Java 6 instead)

Because of this, I have just written an implementation using Java 6 API (using Java 6 javadocs for reference):

  Public class logfileHelper {Private Final Buffed Writer Writer; Public LogFileHelper (file output file) throws IOException {if (! OutputFile.exists ()) // // JavaDoc says it is not certain that the file will be created outfile.createNewFile (); } This.writer = new BufferedWriter (new FileWriter (outputFile, true)); } Public Zero throws a written line (string line) IOException {if (line == blank) {new invalid execution exception ("line can not be zero"); } This.writer.write (line); This.writer.newLine (); This.writer.flush (); // Make sure the line we have written is written and kept if the application crashes} Try the public zero line line (try) (try); } Hold (IOException ioe) {// Your Exception Here Handling}} Public Zero Closure () throws IOException {this.writer.close (); } Public Zero TryClose () {try {this.writer.close ()}} Hold (IOException ioe) {// Exception handling here}}}   

I make exception handling easier Tried XXX ways, as I think you'll use the same everywhere.

With the above category, you can store an example anywhere, write where it is needed and close it on exit. Your best bet for this is a shutdown handler like this:

  runtime.gettime (). AddShutdownHook (New Thread ("Chatlag Shutdown Thread") {@ Override Public Wired Run () {myLogFileHelper.tryClose ();}});   

You will execute the statement when making your LogFileHelper example.

The above code every time you write something - if you want to be super skilled, you can flush less often. To avoid flushing immediately, a legitimate use case would be to write the whole batch of lines at once, although you do not always have to keep flushing and file on disk immediately.

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -