No nonsense, on the horse.
Import Java.io.File;
Import java.io.IOException;
Import Java.io.RandomAccessFile;
Import Java.nio.channels.FileChannel;
Import Java.nio.channels.FileLock;
/**
* @author DBJ
*
*/
public class Mythreadinfowritor {
private String filename;
/**
*
*/
Public Mythreadinfowritor (String fileName) {
This.filename = filename;
}
public void Write (Mythreadinfo tinfo) {
Randomaccessfile out = null;
File File = new file (this.filename);
try {
if (!file.exists ()) {
File.createnewfile ();
out = new Randomaccessfile (file, "RW");
}
out = new Randomaccessfile (file, "RW");
FileChannel fcout = Out.getchannel ();
Filelock flout = null;
while (true) {
try {
Flout = Fcout.lock ();
Break
} catch (Exception e) {
System.out.println ("The other thread is manipulating the file, the current thread sleeps 1000 milliseconds");
try {
Thread.Sleep (1000);
} catch (Interruptedexception E1) {
E1.printstacktrace ();
}
}
}
Long filelength = Out.length ();
Out.seek (filelength);
Out.write (Tinfo.tostring (). GetBytes ("UTF8"));
Flout.release ();
Fcout.close ();
Out.close ();
out = null;
} catch (IOException e) {
File.deleteonexit ();
System.out.println ("Exception encountered:" + e);
}
}
}
Java multithreaded Write file