如何关闭RandomAccessFile

时间:2015-05-28 14:18:48

标签: java file

我试图关闭RandomAccessFile,但资源仍然很忙。

代码:

public boolean isOpen(RandomAccessFile f) {
        try {
            f.length() ;
            return true ;
        }
        catch (IOException e) {
            return false ;
        }
    }
this.rfmFile = new File(filePath);
try {
this.rfmRandomAccessFile = new RandomAccessFile(rfmFile, "rws");
} catch(Exception e){
}finally{
this.rfmRandomAccessFile.close();
}
while(!isOpen(this.rfmRandomAccessFile));
log.debug("I Finally Closed this RAF");

未显示日志,并且线程进入循环。 当我尝试从shell访问我的资源时,它给了我"设备或资源忙"。

访问的唯一方法是kill java process。

1 个答案:

答案 0 :(得分:1)

当您尝试访问RandomAccessFile length()方法时,它已经关闭,因此您无法再访问它。 您可能想要使用File的length()方法。由于RandomAccessFile已经关闭,你的循环无法工作 但我必须承认,我对rfmRandomAccessFile不能真正关闭的低级别原因一无所知。这可能是您的奇怪循环尝试获取已关闭文件大小的副作用。

[edit:]无法使用以下代码重现您的问题:

package com.company;

import java.io.*;

public class Main {

    public static void main(String[] args)  {
        File file = new File("foobar.txt");
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "rws");
            randomAccessFile.write(new byte[]{'f'});
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(randomAccessFile !=null){
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    //doh!
                }
            }
        }
        FileReader reader = null;
        try {
            reader = new FileReader(file);
            char read = (char) reader.read();
            System.out.println("what was written: "+read);
            System.out.println("file size: "+file.length());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(reader !=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    //doh!
                }
            }
        }
    }
}