RandomAccessFile file = new RandomAccessFile(file, "rws");
File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);
FileChannel channel = fis.getChannel();
FileLock fileLock = null;
while(true) {
fileLock = channel.tryLock(0, Long.MAX_VALUE, false); // true表示是共享锁,false则是独享锁定
if(fileLock!=null) break;
else // 有其他线程占据锁
sleep(1000);
}
public class MyFile {
private String fileName;
public MyFile(String fileName) {
this.fileName = fileName;
}
public synchronized void writeData(String data) throws IOException {
String tmpFileName = UUID.randomUUID().toString()+".tmp";
File tmpFile = new File(tmpFileName);
FileWriter fw = new FileWriter(tmpFile);
fw.write(data);
fw.flush();
fw.close();
// now rename temp file to desired name, this operation is atomic operation under most os
if(!tmpFile.renameTo(fileName) {
// we may want to retry if move fails
throw new IOException("Move failed");
}
}
}
public class MyFile {
private String fileName;
public MyFile(String fileName) {
this.fileName = fileName;
}
public synchronized void writeData(String data) throws IOException {
FileWriter fw = new FileWriter(fileName);
fw.write(data);
fw.flush();
fw.close();
}
}
public class MyFile {
private volatile boolean canWrite = true;
private String fileName;
public MyFile(String fileName) {
this.fileName = fileName;
}
public void writeData(String data) {
while(!canWrite) {
try { Thread.sleep(100); } catch(InteruptedException ie) { } // 可以设置一个超时写时间
}
canWrite = false;
// Now write file
canWrite = true;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有