2

All I need help with is testing whether the file is opened or not.

Here is what I have:

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!");}
}
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
user3521205
  • 41
  • 1
  • 1
  • 7

1 Answers1

6

If this

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

doesn't produce an exception, then the file was accessed correctly. However if you need to check if the file is being written to or if it's being otherwise accessed allready, you will need to check if it's locked.

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();
}
Dropout
  • 13,653
  • 10
  • 56
  • 109