gpt4 book ai didi

java - 如何在java中为属性文件提供文件锁?

转载 作者:行者123 更新时间:2023-12-01 11:19:30 27 4
gpt4 key购买 nike

我正在使用属性文件来存储两个变量的计数:

  • TransId
  • RegisNumber

逻辑的工作原理如下:
1) 最初这两个变量被初始化为1并存储在Sequence.properties文件中。
2) RegisNumber 将为 1,而每当进行调用时,都会从 Sequence.properties 文件中获取 TransId 的先前值,并递增到1.

要求是:可以同时对函数executeRegNo()进行'n'次调用,因此存在'n'个进程访问的可能性同时创建 Sequence.properties 文件。

我所做的修改:我尝试放置 fileLock 。代码如下,

public static String executeRegNo() {
File file=new File("C:/Users/abc/Desktop/Files/GetCount.properties");
Properties properties=new Properties();
FileLock lock=null;
if (!file.exists()) {
try
{
file.createNewFile();
properties.setProperty("TransNum", "0");
properties.setProperty("RegId", "1");
properties.store(new FileOutputStream(file), null);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
if (file.canRead()) {
try
{
FileChannel fileChannel=new RandomAccessFile(file, "rw").getChannel(); // 1. modified
lock=fileChannel.lock();//2. modified
properties.load(new FileInputStream(file));
}
catch (IOException e)
{
e.printStackTrace();
}
String transId = properties.getProperty("TransNum");
String RegisId = properties.getProperty("RegId");
properties.setProperty("TransNum", String.valueOf(Integer.parseInt(transId) + 1));
properties.setProperty("RegId", String.valueOf(Integer.parseInt(RegisId)));
try
{
properties.store(new FileOutputStream(file), null);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
String RId = properties.getProperty("RegId");
String TId = properties.getProperty("TransNum");
try {
lock.release(); //3. modified
} catch (IOException e) {

e.printStackTrace();
}
DecimalFormat df = new DecimalFormat("00");
String R = String.valueOf(df.format(Integer.parseInt(RId)));
DecimalFormat df1 = new DecimalFormat("0000");
String T = String.valueOf(df1.format(Integer.parseInt(TId)));
return R + T;
}

我收到的错误是:该进程无法访问该文件,因为另一个进程已锁定该文件的一部分。

FileLock 到底应该放在代码中的什么位置?

请帮助解决问题。

提前致谢。

最佳答案

Where to exactly put the FileLock in the code?

无处可去。文件锁不是线程安全的解决方案。请参阅 Javadoc。

您应该为此使用同步。

或者读写锁。

或者数据库。

关于java - 如何在java中为属性文件提供文件锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31421040/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com