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);
}
}
}
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号