2016-11-29 27 views
1

這是我的方法來壓縮文件到壓縮文件:如何鎖定文件的另一個線程

public void addFilesToArchive(File source, File destination) throws 
IOException, ArchiveException { 

    try (FileOutputStream archiveStream = new FileOutputStream(destination); 
      ArchiveOutputStream archive = new ArchiveStreamFactory() 
        .createArchiveOutputStream(getType(), archiveStream)) { 

     updateSourceFolder(source); 
     generateFileAndFolderList(source); 

     for (String entryName : fileList) { 
      ArchiveEntry entry = getEntry(entryName); 
      archive.putArchiveEntry(entry); 
      archive.closeArchiveEntry(); 
     } 
    } 
} 

的fileList conatains所有文件層次(文件夾和文件)

我想,以防止不同的線程進入壓縮一個目的地在同一時間。

嘗試使用:

FileChannel channel = archiveStream.getChannel(); 
channel.lock(); 

,但它似乎並沒有對大家有所幫助。我怎麼解決這個問題?

回答

1

您正試圖鎖定文件與其他線程,而不是其他進程,這正是文件鎖定不能執行的操作。看到Javadoc。您需要使用同步或信號量。

相關問題