<分区>
Possible Duplicate:
How can I lock a file using java (if possible)
我有两个进程调用两个修改同一个文本文件的 Java 程序。我注意到文本文件的内容缺少数据。我怀疑当一个 java 程序获取到文本文件的写入流时,我认为它会阻止另一个 java 程序修改它(比如当你打开一个文件时,你不能删除该文件)。除了数据库之外,有没有办法解决这个问题? (并不是说 db 解决方案不干净或不优雅,只是我们在操作这个文本文件时写了很多代码)
编辑
原来我针对问题的定位是错误的。我的文本文件中的数据丢失的原因是,
ProcessA
: 不断向文本文件中添加数据行
ProcessB
: 开始时,将文本字段的所有行加载到 List
中.然后它操纵该列表的包含。最后,ProcessB
写回列表,替换文本文件的内容。
这在顺序过程中非常有效。但是一起跑的时候,如果ProcessA
在ProcessB
期间向文件添加数据操纵 List
, 然后当 ProcessB
写 List
退出,无论如何ProcessA
只需添加,将被覆盖。所以我最初的想法是在ProcessB
之前写 List
退出,同步文本文件和 List
之间的数据.所以当我写 List
退出,它将包含所有内容。所以这是我的努力
public void synchronizeFile(){
try {
File file = new File("path/to/file/that/both/A/and/B/write/to");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = channel.lock(); //Lock the file. Block until release the lock
List<PackageLog> tempList = readAllLogs(file);
if(tempList.size() > logList.size()){
//data are in corrupted state. Synchronized them.
for(PackageLog pl : tempList){
if(!pl.equals(lookUp(pl.getPackageLabel().getPackageId(), pl.getPackageLabel().getTransactionId()))){
logList.add(pl);
}
}
}
lock.release(); //Release the file
channel.close();
} catch (IOException e) {
logger.error("IOException: ", e);
}
}
所以 logList
是ProcessB
的当前列表想写出来。所以在写出之前,我读取文件并将数据存储到 tempList
中, 如果 tempList
和 logList
不一样,同步它们。问题是在这一点上,ProcessA
和 ProcessB
当前正在访问该文件,所以当我尝试锁定该文件并从中读取时 List<PackageLog> tempList = readAllLogs(file);
, 我要么得到 OverlappingFileLockException
, 或 java.io.IOException: The process cannot access the file because another process has locked a portion of the file
.请帮我解决这个问题:(
EDIT2:我对 Lock 的理解
public static void main(String[] args){
File file = new File("C:\\dev\\harry\\data.txt");
FileReader fileReader = null;
BufferedReader bufferedReader = null;
FileChannel channel = null;
FileLock lock = null;
try{
channel = new RandomAccessFile(file, "rw").getChannel();
lock = channel.lock();
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String data;
while((data = bufferedReader.readLine()) != null){
System.out.println(data);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
lock.release();
channel.close();
if(bufferedReader != null) bufferedReader.close();
if(fileReader != null) fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我得到了这个错误 IOException: The process cannot access the file because another process has locked a portion of the file