2

I have 10 text files, that I use to store records. In my application, I have couple of operations, e.g write to file and edit file (if the specified line is found I create a temp file and transfer all info there, then delete the old and rename the temp file).

All my clients will have access to the 10 text files, so I want synchronize their activities to maintain data consistency.

I want to lock or synchronize a file if a client is editing or writing, say f1.txt so no other can write/edit to it and increase concurrency by letting another client to edit f2.txt in the same time.

public void writeToFile(String pathname){
File f1 = new File(pathname)
synchronize (f1) {.. // do something}
}

My problem here is that am creating a new file everytime with a specific path.

Please I would appreciate any guidance and help, am you to this.

Thanks

4

1 回答 1

7

如果我理解正确,您希望在特定文件路径上同步(并且文件系统没有以您喜欢的方式执行此操作)。您是正确的,该File对象将不起作用。您需要同步的是文件的名称

public void writeToFile(String pathname){
File f1 = new File(pathname)
synchronize (f1.getCanonicalPath().intern()) {.. // do something}
}

getCanonicalPath方法将为引用相同路径的任何两个对象返回相同的String值。File例如,如果../logs/mylog.txt/var/spool/logs/mylog.txt是同一个文件,它们将具有相同的规范路径。

intern方法为任何两个具有相同的对象返回相同的引用。因此,您最终锁定的是文件规范路径的单例实例。Stringvalue

我认为这可以满足您的需求。

于 2013-11-01T19:04:48.010 回答