如何检查文件是否已打开

时间:2014-04-10 20:44:25

标签: java

我需要帮助的是测试文件是否打开。

这就是我所拥有的:

public static void main(String[] args) {

    //Prompt user to input file name
    SimpleIO.prompt("Enter File name: ");
    String fileName = SimpleIO.readLine();

    //Create file object 
    File file = new File (fileName);

    //Check to see if file is opened 

    if (!file.exists()){
        System.out.println("The file you entered either do not exist or the name is spelled wrong.\nProgram is now being terminated.\nGoodbye!");}
}

1 个答案:

答案 0 :(得分:3)

如果这个

//Create file object 
File file = new File (fileName);

没有产生异常,然后正确访问了该文件。但是,如果您需要检查是否正在写入文件,或者是否已经全部访问该文件,则需要检查它是否已被锁定。

File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

FileLock lock = channel.lock();
try {
    lock = channel.tryLock();
    System.out.print("file is not locked");
} catch (OverlappingFileLockException e) {
    System.out.print("file is locked");
} finally {
    lock.release();
}