[英]Pause the execution of Java if files are used
我的應用程序寫入Excel文件。 有時可以使用該文件,在這種情況下會拋出FileNotFoundException,然后我不知道如何更好地處理它。
我告訴用戶該文件已被使用,並且在此消息之后,我不想關閉該應用程序,而是在文件可用時停止並等待(假設它是由同一用戶打開的)。 但是我不知道如何實現它。 file.canWrite()不起作用,即使打開文件,它也會返回true,要使用FileLock並檢查鎖是否可用,我需要打開一個流,但是會拋出FileNotFoundException(我一直在考慮檢查鎖定忙碌的等待時間,我知道這不是一個好的解決方案,但是我找不到另一個解決方案。
如果可以以某種方式幫助理解我的問題,這是我的代碼的一部分:
File file = new File(filename);
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
FileChannel channel = out.getChannel();
FileLock lock = channel.lock();
if (lock == null) {
new Message("lock not available");
// to stop the program here and wait when the file is available, then resume
}
// write here
lock.release();
}
catch (IOException e) {
new Message("Blocked");
// or to stop here and then create another stream when the file is available
}
對我來說更困難的是它寫入不同的文件,並且如果第一個文件可用,但第二個文件不可用,則它將更新一個文件然后停止,如果我重新啟動程序,它將對其進行更新。再次,所以在所有文件都可用之前,我不允許程序將文件寫入文件。
我相信應該有一個通用的解決方案,因為它必須是Windows中處理此類情況的常見問題,但是我找不到它。
要等待文件存在,可以進行簡單循環:
File file = new File(filename);
while (!file.exists()) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) { /* safe to ignore */ }
}
更好的解決方案可以使用WatchService
但要實現的代碼更多。
File.canWrite
方法僅告訴您是否可以寫入路徑。 如果路徑命名的文件不存在,則將返回false
。 您可以使用canRead
方法代替exists
於上述循環中的方法。
要使用文件鎖,文件必須首先存在,因此也不起作用。
確保可以寫入文件的唯一方法是嘗試打開它。 如果該文件不存在,則java.io
API將創建它。 要打開一個文件進行寫入而不創建它,可以使用java.nio.file.Files
類:
try (OutputStream out = Files.newOutputStream(file.toPath(),
StandardOpenOption.WRITE))
{
// exists and is writable
} catch (IOException) {
// doesn't exist or can't be opened for writing
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.