Java 多線程寫文件
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("其他線程正在操作該文件,當前線程休眠1000毫秒");
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);
}
}
}</pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!