2016-07-29 34 views
1

這是我見過的將行追加到文件中的最清晰的方式。 (並創建該文件,如果它不存在)使用FileLock將文件追加到文件

String message = "bla"; 
Files.write(
    Paths.get(".queue"), 
    message.getBytes(), 
    StandardOpenOption.CREATE, 
    StandardOpenOption.APPEND); 

但是,我需要添加(OS)鎖定它。我瀏覽過FileLock的例子,但是在Oracle Java教程中找不到任何規範的例子,而且這些API對我來說是非常難以理解的。

回答

2

您可以鎖定一個文件,檢索它的流通道並鎖定它。

東西amongs線:

new FileOutputStream(".queue").getChannel().lock(); 

您還可以使用tryLock取決於如何順利,你想要的。

我們寫和鎖定,您的代碼將是這樣的:

try(final FileOutputStream fos = new FileOutputStream(".queue", true); 
    final FileChannel chan = fos.getChannel()){ 
    chan.lock(); 
    chan.write(ByteBuffer.wrap(message.getBytes())); 
} 

注意,在這個例子中,我用Files.newOutputStream添加您打開選項。

+0

@fred已取得了計算機,編輯。這是正確的,如果所需的唯一選項是append,那麼我們可以直接傳遞一個布爾值作爲構造函數之一,期望append標誌。 –

2

不在此代碼中。您將不得不通過FileChannel打開文件,獲取鎖定,執行寫入操作,關閉文件。或者放開鎖並保持文件打開,如果你願意的話,所以你只需要下一次鎖定。請注意,文件鎖只能防止其他文件鎖定,而不是針對您發佈的代碼。

1

您可以將鎖應用於FileChannel。

try { 
     // Get a file channel for the file 
     File file = new File("filename"); 
     FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); 

     // Use the file channel to create a lock on the file. 
     // This method blocks until it can retrieve the lock. 
     FileLock lock = channel.lock(); 

     /* 
      use channel.lock OR channel.tryLock(); 
     */ 

     // Try acquiring the lock without blocking. This method returns 
     // null or throws an exception if the file is already locked. 
     try { 
      lock = channel.tryLock(); 
     } catch (OverlappingFileLockException e) { 
      // File is already locked in this thread or virtual machine 
     } 

     // Release the lock - if it is not null! 
     if(lock != null) { 
      lock.release(); 
     } 

     // Close the file 
     channel.close(); 
    } catch (Exception e) { 
    } 

欲瞭解更多你可以通過這個教程:

  1. How can I lock a file using java (if possible)
  2. Java FileLock for Reading and Writing