Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何检查文件是否已打开_Java - Fatal编程技术网

Java 如何检查文件是否已打开

Java 如何检查文件是否已打开,java,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 (fileNa

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

以下是我所拥有的:

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!");}
}
如果这

//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();
}
如果这

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

对于将来的问题:看一看。对于将来的问题:看一看。你能告诉我你是从哪里学的吗?我是说书或文章?你能告诉我你是从哪里学的吗?我是说书还是什么文章?