Topic: 怎么判断一个文件已经打开?

  Print this page

1.怎么判断一个文件已经打开? Copy to clipboard
Posted by: kempguan
Posted on: 2003-10-20 11:09

在java中,怎么来判断file对象已经打开?
或者已经存在的一个文件已经被打开?

2.Re:怎么判断一个文件已经打开? [Re: kempguan] Copy to clipboard
Posted by: dog72
Posted on: 2003-10-20 11:16

没办法,至少在1.3以下。自己记录吧.

3.Re:怎么判断一个文件已经打开? [Re: kempguan] Copy to clipboard
Posted by: kempguan
Posted on: 2003-10-20 11:27

我现在是1.4,那位老兄有什么方法?

4.Re:怎么判断一个文件已经打开? [Re: kempguan] Copy to clipboard
Posted by: hegong121
Posted on: 2003-10-21 09:07

看看nio下面的FileChannel关于文件锁的部分,可能用得着

5.Re:怎么判断一个文件已经打开? [Re: kempguan] Copy to clipboard
Posted by: drum
Posted on: 2003-10-21 10:03

nio可以实现
nio是对操作系统级io的直接操作,所以它提供了系统级lock文件机制

6.Re:怎么判断一个文件已经打开? [Re: kempguan] Copy to clipboard
Posted by: kempguan
Posted on: 2003-10-21 10:44

楼上老兄,给个简单例子

7.Re:怎么判断一个文件已经打开? [Re: kempguan] Copy to clipboard
Posted by: drum
Posted on: 2003-10-21 13:15

import java.io.RandomAccessFile;
import java.nio.channels.*;
public class TestFileLock {
  public static void main(String[] args) throws Exception{
    Runnable r = new Runnable(){
      public void run()
      {
        try{
          RandomAccessFile raf = new RandomAccessFile ("c:\\test.txt","rw");
          FileChannel fc = raf.getChannel();
          FileLock lock = fc.tryLock();
          if(lock!=null)
          {
              System.out.println(Thread.currentThread().getName()+": Open the File");
              Thread.sleep(100000);
              lock.release();
              System.out.println(Thread.currentThread().getName()+": Releae the File.");
          }
          else
            System.out.println(Thread.currentThread().getName()+": Because the file is being used, you can't get the file lock.");      
        }catch(Exception e)
        {
          
        }

      }
    };
new Thread(r).start();
   new Thread(r).start();

  

  }
  
}

如果你把sleep的时间设的长些,然后运行它的同时你用记事本修改这个test.txt会收到“进程无法访问文件”的错误信息

8.Re:怎么判断一个文件已经打开? [Re: kempguan] Copy to clipboard
Posted by: hegong121
Posted on: 2003-10-21 13:26

下面是一个简单的例子,关于new io的内容比较多,原理也比较复杂,我就不在这里说明了,你可以在网上查查nio的相关内容

import java.nio.channels.*;
import java.io.*;
public class Untitled1
{

public Untitled1()
{
}
public static void main(String[] args)
{
try
{
FileOutputStream a=new FileOutputStream("c:\\性能.doc",true);
FileChannel c=a.getChannel() ;
FileLock l=c.tryLock();
if(l==null)System.out.println("file is locked!") ;
a.close() ;
}catch(Exception ex){ex.printStackTrace() ;}
}
}

9.Re:怎么判断一个文件已经打开? [Re: kempguan] Copy to clipboard
Posted by: hegong121
Posted on: 2003-10-21 13:32

哦,原来drum 已经回了。

10.Re:怎么判断一个文件已经打开? [Re: kempguan] Copy to clipboard
Posted by: kempguan
Posted on: 2003-10-21 16:43

谢谢各位,我已实现该功能。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923