Java文件方法“canWrite()”可以吗?支持锁定? [英] Can the Java File method "canWrite()" support locking?

查看:1109
本文介绍了Java文件方法“canWrite()”可以吗?支持锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java应用程序监视传入XML文件的文件夹。当检测到新文件时,我需要测试当前没有更新并关闭的文件。我的想法是使用文件。 canWrite()来测试这个。这样做有什么问题吗?这是一个很好的方法来测试一个文件已被完全写入?



其他的想法是:


  • 解析传入的XML文件并测试
    的结尾标记。
  • 检查EoF字符。


我不确定这些方法中的任何一个都可以处理所有的情况。

解决方案

不,canWrite不适合这个目的。一般情况下,即使有另一个进程正在写入,文件也是可写的。



需要更高级别的协议来协调锁定。如果您打算在单个平台上使用此代码,则可以使用 NIO的FileLock工具。但仔细阅读文档,并注意到,在许多平台上,锁只是咨询。另一种方法是让一个进程用你的进程写一个名字的文件将无法识别,然后在写入完成时将文件重命名为可识别的名称。在大多数平台上,如果源和目标是相同的文件系统卷,则重命名操作是原子操作。名称更改可能使用不同的文件扩展名,甚至将文件从一个目录移动到另一个目录(在同一卷)。

因为在这种情况下,您正在工作使用XML,寻找一个关闭标签是可行的,但它并不是万无一失的 - 如果在最终的标记之后有评论,或者写作者或者根本不写有效的XML?

寻找EOF将不工作。即使在作者刚刚打开文件并且还没有写入任何内容的情况下,总会有一个EOF。如果不是这样,最简单的方法就是让读者在文件出现后立即开始解析;它会阻止,直到作者关闭文件。但是文件系统不能这样工作。每个文件都有一个结束,即使某个进程正在移动它。


I have a Java application that monitors a folder for incoming XML files. When a new file is detected I need to test the file that it is not currently being updated and is closed. My thought is to use File.canWrite() to test this. Is there any issue with doing this? Is this a good way to test that a file has been completely written?

Other ideas I am throwing around are:

  • Parse the incoming XML file and test that the closing tag is there.
  • Check for the EoF character.

I just am not sure that any of these methods will handle all scenarios.

解决方案

No, canWrite is not suitable for this purpose. In general the file will be writable even if another process is writing.

You need a higher level protocol to coordinate the locking. If you plan to use this code on a single platform, you may be able to use NIO's FileLock facility. But read the documentation carefully, and note that on many platforms, the lock is only advisory.

Another approach is to have one process write the file with a name that your process won't recognize, then rename the file to a recognizable name when the write is complete. On most platforms, the rename operation is atomic if the source and destination are the same file system volume. The name change might use a different file extension, or even moving the file from one directory to another (on the same volume).

Since in this case you are working exclusively with XML, looking for a close tag would work, but it isn't foolproof—what if there are comments after the final markup, or the writer or simply doesn't write valid XML?

Looking for the EOF will not work. There will always be an EOF, even when the writer has just opened the file and hasn't written anything yet. If this weren't so, the easiest thing would be to allow the reader to start parsing as soon as the file showed up; it would simply block until the writer closed the file. But the file system doesn't work this way. Every file has an end, even if some process is currently moving it.

这篇关于Java文件方法“canWrite()”可以吗?支持锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆