2014-04-10 247 views
0

我需要幫助的是檢測文件是否打開。如何檢查文件是否打開

以下是我有:

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!");} 
} 
+0

對於將來的問題:請看看[幫助中心](http://stackoverflow.com/help/how-to-ask)。 –

回答

0

如果

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

不會產生異常,則該文件被正確地訪問。但是,如果您需要檢查文件是否正在寫入,或者是否正在以其他方式訪問allready,則需要檢查它是否被鎖定。

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(); 
} 
+0

你能告訴我你在哪裏學到了這個嗎?我的意思是書或一些文章? –