使用FileChannels进行Java内存管理

时间:2011-05-23 23:05:36

标签: java memory-management

我正在使用下面显示的checkForErrors方法来检查txt文件中的错误。该方法执行预期,期望与方法参数f相关联的OS文件句柄未被释放。这会导致下游外部.exe失败,并显示错误消息“进程无法访问该文件,因为该文件正由另一个进程使用。”

它是否是我未能解决的明显的内存管理问题?

private boolean checkForErrors(File f)
{
    FileInputStream fis = null;
    FileChannel fc = null;

    try
    {
        if (!f.exists())
        {
            return true;
        }

        // get a Channel for the source file
        fis = new FileInputStream(f);
        fc = fis.getChannel();

        Pattern errorPattern = Pattern.compile("ERROR");
        Pattern eoPattern = Pattern.compile("END OF OUTPUT ");

        // get a CharBuffer from the source file
        ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size());
        Charset cs = Charset.forName("8859_1");
        CharsetDecoder cd = cs.newDecoder();
        CharBuffer cb = cd.decode(bb);

        // check for the presence of the ERROR keyword
        Matcher eP = errorPattern.matcher(cb);

        if (eP.find())
        {
            return true;
        }

        // check for the ABSENCE of the end of output keywords
        Matcher eoP = eoPattern.matcher(cb);

        if (!eoP.find())
        {
            return true;
        }
    }
    catch (IOException ex)
    {
        LOG.log(Level.INFO, null, ex);

        return true;
    }
    finally
    {
        try
        {
            if (fc != null)
            {
                fc.close();
                fc = null;
            }

            if (fis != null)
            {
                fis.close();
                fis = null;
            }
        }
        catch (IOException ex)
        {
            LOG.log(Level.INFO, null, ex);
        }
    }

    return false;
}

0 个答案:

没有答案