2014-02-26 103 views
0

我有一个文件说text.csv从我的Java程序试图读取/写入。在Java中写锁定

有没有办法在Java中检测此文件是否打开,以便在文件被某些用户通过“双击”打开时进行写入?如果是这样,怎么样?我在寻找这样的代码:

if(isOpenForWrite(File file){ 
//say text.csv is already opened ... 
} 

任何有用的文档或其他资源是值得欢迎的。检查此

+0

http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ314_030.htm – StanislavL

+0

@ StanislavL该锁定是否会影响访问文件的其他进程? –

+0

@Kunal Krishna你看过这个 “http://stackoverflow.com/questions/1390592/java-check-if-file-is-already-open” – saravanakumar

回答

0

最好的办法是检查是否可以重命名文件

String fileName = "C:\\Text.xlsx"; 
File file = new File(fileName); 

// try to rename the file with the same name 
File sameFileName = new File(fileName); 

if(file.renameTo(sameFileName)){ 
    // if the file is renamed 
    System.out.println("file is closed");  
}else{ 
    // if the file didnt accept the renaming operation 
    System.out.println("file is opened"); 
} 

或使用Apache通用IO库

+1

请注意,重命名可以工作,并且_then_用户可以打开该文件。 –

+0

@SotiriosDelimanolis同样可以发生任何检查,所以我不认为这是一个执行问题。 – crzbt

+0

我只是不认为它会很可靠。 –

0

我会用FileChannel.lock做到这一点。

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

    // Blocks until it can retrieve the lock. 
    FileLock lock = channel.lock(); 
    // Try acquiring the lock without blocking. 
    // lock is null or exception if the file is already locked. 

    try { 
     lock = channel.tryLock(); 
    } catch (OverlappingFileLockException e){} 


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

来源:Java: Check if file is already open

使用此,我发现这个上面吩咐链接

boolean isFileUnlocked = false; 
    try { 
    org.apache.commons.io.FileUtils.touch(yourFile); 
    isFileUnlocked = true; 
    } catch (IOException e) { 
    isFileUnlocked = false; 
    } 

    if(isFileUnlocked){ 
    // Do stuff you need to do with a file that is NOT locked. 
    } else { 
    // Do stuff you need to do with a file that IS locked 
    }