用于基于文件的进程通信的Java文件锁定机制 [英] Java file locking mechanism for file based process communication
问题描述
我有两个java进程(JAR),一个是每1分钟写一个文本文件,另一个是读取该文件并调用一个Web服务将数据存储在数据库中。
I have two java process (JAR) one is writing to a text file on every 1 min and another is reading that file and call a web service to store data in database.
有没有办法在写入模式时锁定文件?我观察到当 wvdial
正在拨打调制解调器时,我想在/var/lock/ttyUSB0..LOCK中创建一个锁文件。我希望这种程序如果文件处于写入模式,另一个进程可以等到写完成。写完程序后可以读取文件内容。
Is there any way to lock the file when it is on write mode? I have observed that when wvdial
is dialing a modem its create a lock file in /var/lock/ttyUSB0..LOCK I think. I want a this kind of procedure if the file is on write mode the another process could wait till write done. After writing the process can read the file content.
请指导我解决我的问题。
Please guide me to solve my issue.
谢谢
推荐答案
也许这堂课可以帮助你 http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileLock.html
Maybe this class can help you http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileLock.html
编辑:这篇文章可能已涵盖主题如何使用java锁定文件(如果可能)
This post might already be covering the subject How can I lock a file using java (if possible)
例如:
FileInputStream in = new FileInputStream(file);
try
{
java.nio.channels.FileLock lock = in.getChannel().lock();
try
{
//write
}
finally
{
lock.release();
}
}
finally
{
in.close();
}
现在正在阅读过程中:
FileInputStream in = new FileInputStream(file);
try
{
FileLock lock = in.getChannel().tryLock();
if (lock == null)
{
//file is locked, wait or do something else
}
else
{
try
{
//read
}
finally
{
lock.release();
}
}
}
finally
{
in.close();
}
这篇关于用于基于文件的进程通信的Java文件锁定机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!