Управление памятью Java с помощью FileChannels - PullRequest
0 голосов
/ 24 мая 2011

Я использую метод checkForErrors, показанный ниже, для проверки ошибок в текстовом файле. Метод выполняет ожидаемое ожидание того, что дескриптор файла ОС, связанный с параметром метода f, не освобождается. Это приводит к сбою внешнего внешнего .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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...