Example usage for java.io RandomAccessFile seek

List of usage examples for java.io RandomAccessFile seek

Introduction

In this page you can find the example usage for java.io RandomAccessFile seek.

Prototype

public void seek(long pos) throws IOException 

Source Link

Document

Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

Usage

From source file:twister.core.io.input.Tailer.java

/**
 * Follows changes in the file, calling the TailerListener's handle method for each new line.
 *///from ww w .j a v a  2s . c om
public void run() {
    RandomAccessFile reader = null;
    try {
        long last = 0; // The last time the file was checked for changes
        long position = 0; // position within the file
        // Open the file
        while (run && reader == null) {
            try {
                reader = new RandomAccessFile(file, "r");
            } catch (FileNotFoundException e) {
                listener.fileNotFound();
            }

            if (reader == null) {
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                }
            } else {
                // The current position in the file
                position = end ? file.length() : 0;
                last = System.currentTimeMillis();
                reader.seek(position);
            }
        }

        while (run) {

            // Check the file length to see if it was rotated
            long length = file.length();

            if (length < position) {

                // File was rotated
                listener.fileRotated();

                // Reopen the reader after rotation
                try {
                    // Ensure that the old file is closed iff we re-open it successfully
                    RandomAccessFile save = reader;
                    reader = new RandomAccessFile(file, "r");
                    position = 0;
                    // close old file explicitly rather than relying on GC picking up previous RAF
                    IOUtils.closeQuietly(save);
                } catch (FileNotFoundException e) {
                    // in this case we continue to use the previous reader and position values
                    listener.fileNotFound();
                }
                continue;
            } else {

                // File was not rotated

                // See if the file needs to be read again
                if (length > position) {

                    // The file has more content than it did last time
                    last = System.currentTimeMillis();
                    position = readLines(reader);

                } else if (FileUtils.isFileNewer(file, last)) {

                    /* This can happen if the file is truncated or overwritten
                     * with the exact same length of information. In cases like
                     * this, the file position needs to be reset
                     */
                    position = 0;
                    reader.seek(position); // cannot be null here

                    // Now we can read new lines
                    last = System.currentTimeMillis();
                    position = readLines(reader);
                }
            }
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
            }
        }

    } catch (Exception e) {

        listener.handle(e);

    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.dotmarketing.servlets.taillog.Tailer.java

/**
 * Follows changes in the file, calling the TailerListener's handle method for each new line.
 *//*from w ww .  j  a  va  2  s .  co  m*/
public void run() {
    RandomAccessFile reader = null;
    try {
        long last = 0; // The last time the file was checked for changes
        long position = 0; // position within the file
        // Open the file
        while (run && reader == null) {
            try {
                reader = new RandomAccessFile(file, "r");
            } catch (FileNotFoundException e) {
                listener.fileNotFound();
            }

            if (reader == null) {
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                }
            } else {
                // The current position in the file
                position = end ? file.length() : startPosition;
                last = System.currentTimeMillis();
                reader.seek(position);
                readLine(reader);
                position = reader.getFilePointer();
            }
        }

        while (run) {

            // Check the file length to see if it was rotated
            long length = file.length();

            if (length < position) {

                // File was rotated
                listener.fileRotated();

                // Reopen the reader after rotation
                try {
                    // Ensure that the old file is closed iff we re-open it successfully
                    RandomAccessFile save = reader;
                    reader = new RandomAccessFile(file, "r");
                    position = 0;
                    // close old file explicitly rather than relying on GC picking up previous RAF
                    IOUtils.closeQuietly(save);
                } catch (FileNotFoundException e) {
                    // in this case we continue to use the previous reader and position values
                    listener.fileNotFound();
                }
                continue;
            } else {

                // File was not rotated

                // See if the file needs to be read again
                if (length > position) {

                    // The file has more content than it did last time
                    last = System.currentTimeMillis();
                    position = readLines(reader);

                } else if (FileUtils.isFileNewer(file, last)) {

                    /* This can happen if the file is truncated or overwritten
                     * with the exact same length of information. In cases like
                     * this, the file position needs to be reset
                     */
                    position = 0;
                    reader.seek(position); // cannot be null here

                    // Now we can read new lines
                    last = System.currentTimeMillis();
                    position = readLines(reader);
                }
            }
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
            }
        }

    } catch (Exception e) {

        listener.handle(e);

    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            Logger.error(this.getClass(), "Unable to close: " + e.getMessage());
        }

    }
}

From source file:com.limegroup.gnutella.metadata.MP3DataEditor.java

/**
 * Actually writes the ID3 tags out to the ID3V1 section of mp3 file.
 *///from   w  ww .j  av  a 2  s. c  om
private int writeID3V1DataToDisk(RandomAccessFile file) {
    byte[] buffer = new byte[30];//max buffer length...drop/pickup vehicle

    //see if there are ID3 Tags in the file
    String tag = "";
    try {
        file.readFully(buffer, 0, 3);
        tag = new String(buffer, 0, 3);
    } catch (EOFException e) {
        return LimeXMLReplyCollection.RW_ERROR;
    } catch (IOException e) {
        return LimeXMLReplyCollection.RW_ERROR;
    }
    //We are sure this is an MP3 file.Otherwise this method would never
    //be called.
    if (!tag.equals("TAG")) {
        //Write the TAG
        try {
            byte[] tagBytes = "TAG".getBytes();//has to be len 3
            file.seek(file.length() - 128);//reset the file-pointer
            file.write(tagBytes, 0, 3);//write these three bytes into the File
        } catch (IOException ioe) {
            return LimeXMLReplyCollection.BAD_ID3;
        }
    }
    LOG.debug("about to start writing to file");
    boolean b;
    b = toFile(title_, 30, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_TITLE;
    b = toFile(artist_, 30, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_ARTIST;
    b = toFile(album_, 30, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_ALBUM;
    b = toFile(year_, 4, file, buffer);
    if (!b)
        return LimeXMLReplyCollection.FAILED_YEAR;
    //comment and track (a little bit tricky)
    b = toFile(comment_, 28, file, buffer);//28 bytes for comment
    if (!b)
        return LimeXMLReplyCollection.FAILED_COMMENT;

    byte trackByte = (byte) -1;//initialize
    try {
        if (track_ == null || track_.equals(""))
            trackByte = (byte) 0;
        else
            trackByte = Byte.parseByte(track_);
    } catch (NumberFormatException nfe) {
        return LimeXMLReplyCollection.FAILED_TRACK;
    }

    try {
        file.write(0);//separator b/w comment and track(track is optional)
        file.write(trackByte);
    } catch (IOException e) {
        return LimeXMLReplyCollection.FAILED_TRACK;
    }

    //genre
    byte genreByte = getGenreByte();
    try {
        file.write(genreByte);
    } catch (IOException e) {
        return LimeXMLReplyCollection.FAILED_GENRE;
    }
    //come this far means we are OK.
    return LimeXMLReplyCollection.NORMAL;

}

From source file:au.org.ala.layers.dao.ObjectDAOImpl.java

private HashMap<String, Object> getGridIndexEntry(String path, String objectId) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    RandomAccessFile raf = null;
    try {//from ww  w . ja  v  a2  s .co m
        raf = new RandomAccessFile(path + ".wkt.index.dat", "r");

        int s2 = Integer.parseInt(objectId);

        // it is all in order, seek to the record
        int recordSize = 4 * 7; // 2 int + 5 float
        int start = raf.readInt();
        raf.seek(recordSize * (s2 - start));

        map.put("gn", raf.readInt());
        map.put("charoffset", raf.readInt());
        map.put("minx", raf.readFloat());
        map.put("miny", raf.readFloat());
        map.put("maxx", raf.readFloat());
        map.put("maxy", raf.readFloat());
        map.put("area", raf.readFloat());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (raf != null) {
                raf.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    return map;
}

From source file:com.googlecode.psiprobe.Utils.java

public static void sendFile(HttpServletRequest request, HttpServletResponse response, File file)
        throws IOException {
    OutputStream out = response.getOutputStream();
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    try {//  www. j a va 2s. c o  m
        long fileSize = raf.length();
        long rangeStart = 0;
        long rangeFinish = fileSize - 1;

        // accept attempts to resume download (if any)
        String range = request.getHeader("Range");
        if (range != null && range.startsWith("bytes=")) {
            String pureRange = range.replaceAll("bytes=", "");
            int rangeSep = pureRange.indexOf("-");

            try {
                rangeStart = Long.parseLong(pureRange.substring(0, rangeSep));
                if (rangeStart > fileSize || rangeStart < 0) {
                    rangeStart = 0;
                }
            } catch (NumberFormatException e) {
                // ignore the exception, keep rangeStart unchanged
            }

            if (rangeSep < pureRange.length() - 1) {
                try {
                    rangeFinish = Long.parseLong(pureRange.substring(rangeSep + 1));
                    if (rangeFinish < 0 || rangeFinish >= fileSize) {
                        rangeFinish = fileSize - 1;
                    }
                } catch (NumberFormatException e) {
                    // ignore the exception
                }
            }
        }

        // set some headers
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Length", Long.toString(rangeFinish - rangeStart + 1));
        response.setHeader("Content-Range", "bytes " + rangeStart + "-" + rangeFinish + "/" + fileSize);

        // seek to the requested offset
        raf.seek(rangeStart);

        // send the file
        byte[] buffer = new byte[4096];

        long len;
        int totalRead = 0;
        boolean nomore = false;
        while (true) {
            len = raf.read(buffer);
            if (len > 0 && totalRead + len > rangeFinish - rangeStart + 1) {
                // read more then required?
                // adjust the length
                len = rangeFinish - rangeStart + 1 - totalRead;
                nomore = true;
            }

            if (len > 0) {
                out.write(buffer, 0, (int) len);
                totalRead += len;
                if (nomore) {
                    break;
                }
            } else {
                break;
            }
        }
    } finally {
        raf.close();
    }
}

From source file:org.kuali.student.git.model.SvnRevisionMapper.java

private InputStream getInputStream(RevisionMapOffsetProvider offsetProvider, RandomAccessFile dataFile)
        throws IOException {

    RevisionMapOffset revisionOffset = offsetProvider.getRevisionMapOffset();

    if (revisionOffset == null)
        return null;

    byte[] data = new byte[(int) revisionOffset.getTotalBytes()];

    dataFile.seek(revisionOffset.getStartBtyeOffset());

    dataFile.readFully(data);// w ww  . j av  a2s  .c  o  m

    return new BZip2CompressorInputStream(new ByteArrayInputStream(data));

}

From source file:org.mhisoft.wallet.service.AttachmentService.java

public FileAccessTable read(String dataFile, final PBEEncryptor encryptor) {
    logger.fine("\n\nread attachment file:" + dataFile);
    FileAccessTable t = null;//w  w w .  ja  v  a2  s.c o m
    RandomAccessFile fileIn = null;
    try {
        File fIn = new File(dataFile);
        if (!fIn.exists()) {
            return t;
        }

        fileIn = new RandomAccessFile(dataFile, "rw");
        int numberOfEntries = fileIn.readInt();
        t = new FileAccessTable();
        long pos = 4;
        int readBytes = 0;
        for (int i = 0; i < numberOfEntries; i++) {

            fileIn.seek(pos);

            /* UUIID and position */
            String UUID = FileUtils.readString(fileIn);
            FileAccessEntry fileAccessEntry = new FileAccessEntry(UUID);
            pos += 40;
            logger.fine("Read entry, UUID:" + UUID);

            /*  accessflag */
            fileAccessEntry.setAccessFlag(FileAccessFlag.values[fileIn.readInt()]);
            pos += 4;
            logger.fine("\t access flag:" + fileAccessEntry.getAccessFlag());

            /*  pos */
            fileAccessEntry.setPosition(fileIn.readLong());
            pos += 8;
            logger.fine("\t position:" + fileAccessEntry.getPosition());

            /* read filename */
            ReadContentVO vo = readCipherParameter(fileIn, pos);
            pos = vo.pos;
            int encSize_FileName = fileIn.readInt();
            pos += 4;
            byte[] _encedBytes = new byte[encSize_FileName];
            fileIn.readFully(_encedBytes);
            pos += encSize_FileName;
            byte[] byte_filename = encryptor.decrypt(_encedBytes, vo.algorithmParameters);
            fileAccessEntry.setFileName(StringUtils.bytesToString(byte_filename));
            logger.fine("\t file name:" + fileAccessEntry.getFileName());

            /* attachment */
            vo = readCipherParameter(fileIn, pos);
            pos = vo.pos;
            fileAccessEntry.setAlgorithmParameters(vo.algorithmParameters);

            /*#5  size of the content (int): 4 bytes */
            int encSize = fileIn.readInt();
            pos += 4;

            fileAccessEntry.setPosOfContent(pos);
            fileAccessEntry.setEncSize(encSize);
            logger.fine("\t encSize:" + encSize);

            if (fileAccessEntry.getAccessFlag() != FileAccessFlag.Delete)
                t.addEntry(fileAccessEntry);
            else {
                logger.fine("\tentries is marked as deleted.");
                t.deletedEntries++;
            }

            /* #6 file content */
            pos += encSize;

            /* delay read it on demand
            byte[] _encBytes =readFileContent(dataFile, pos, encSize ) ;
            byte[] fileContent = encryptor.decrypt(_encBytes, algorithmParameters);
            pos +=  fileContent.length;
                    
            fileAccessEntry.setFileContent(fileContent);
            fileAccessEntry.setSize(fileContent.length); //decrypted size.
            */

        }

        fileIn.close();
        fileIn = null;

    } catch (Exception e) {
        e.printStackTrace();
        DialogUtils.getInstance().error("Error occurred in reading attachments.", e.getMessage());
    } finally {
        if (fileIn != null)
            try {
                fileIn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    DebugUtil.append(
            "Attachment Store total entries:" + t.getSize() + "\n" + "Orphan records :" + t.deletedEntries);

    return t;
}

From source file:org.gbif.harvest.digir.DigirMetadataHandler.java

/**
 * Issues a metadata request to a DiGIR provider. It then collects metadata
 * about the different resources located behind that provider's access
 * point./*from w  ww.  ja  va  2s.co m*/
 * The collected metadata for each resource, like the name (code), count,
 * etc. is written to a file.
 * Iterating over this file, a new BioDatasource is created for each
 * resource, with its name, count, and other attributes all set accordingly.
 * Note that the name of each new BioDatasource is the concatenation of the
 * Provider and resource code.
 *
 * @param name      of the datasource
 * @param url       of the datasource
 * @param uddiKey   of the datasource
 * @param directory to save files to
 * @param params    map of the datasource
 *
 * @throws HarvesterException thrown if method fails
 */
public void issueMetadata(String name, String url, String uddiKey, String directory, Map<String, Object> params)
        throws HarvesterException {
    log.info("start.issueMetadata");

    // Determine the protocol
    // For now use default protocol as this is the only one needed at metadata level
    String protocol = DEFAULT_PROTOCOL;

    // populate element of interest maps from the mapping file's properties
    populateElementOfInterestsMapsFromMappingFile(METADATA_MAPPING_FILE_NAME, protocol);

    // send metadata request and get response as ByteArrayInputStream
    ByteArrayInputStream metadataResponse = metadataRequest(url, directory, protocol);

    // collect resources metadata, including contact metadata, into
    // separate output files
    processAllMetadata(metadataResponse, directory);

    // recover our metadata files
    File resourcesFile = new File(directory,
            DigirMetadataHandler.RESOURCES_WITH_COUNT_FILENAME.concat(Constants.TEXT_FILENAME_EXTENSION));
    File contactsFile = new File(directory,
            Constants.CONTACT_FILENAME.concat(Constants.TEXT_FILENAME_EXTENSION));

    // Iterate over resource metadata file, and resource contact metadata file
    // For each resource's contacts, write a new contact metadata file
    // For each resource create a new BioDatasource
    // NOTE: it is in the BioDatasource's directory that the contact metadata
    // file is saved
    RandomAccessFile contactsRaf = null;
    RandomAccessFile resourcesRaf = null;
    try {
        contactsRaf = new RandomAccessFile(contactsFile, "r");
        contactsRaf.seek(0L);
        String contactLine = fileUtils.readUTFLine(contactsRaf);

        // put the header column properties into a list (minus line number)
        List<String> contactPropertiesList = retrieveStringListFromLine(contactLine);
        contactLine = fileUtils.readUTFLine(contactsRaf);
        int contactLineNumber = -1;
        if (StringUtils.isNotBlank(contactLine)) {
            contactLineNumber = Integer.valueOf(fileUtils.getDelimitedPart(contactLine, "\t", 0));
        }

        // Open a file cursor to the resources and contacts files
        resourcesRaf = new RandomAccessFile(resourcesFile, "r");
        resourcesRaf.seek(0L);
        String resourceLine = fileUtils.readUTFLine(resourcesRaf);
        int resourceLineNumber = 1;

        // put the header column properties into an array
        String[] resourceProperties = tabPattern.split(resourceLine);
        // remove all line breaking characters
        resourceProperties = fileUtils.removeLineBreakingCharacters(resourceProperties);

        while ((resourceLine = fileUtils.readUTFLine(resourcesRaf)) != null) {
            // set the position of the cursor
            resourceLineNumber = Integer.valueOf(fileUtils.getDelimitedPart(resourceLine, "\t", 0));
            Map<String, Object> newParams = new HashMap<String, Object>();
            newParams.putAll(params);

            String schemaLocation = null;
            String conceptualSchema = "";
            String recordCount = "0";
            for (int columnIndex = 1; columnIndex < resourceProperties.length; columnIndex++) {
                String property = resourceProperties[columnIndex];
                String value = fileUtils.getDelimitedPart(resourceLine, "\t", columnIndex);
                System.out.println("the value for property: " + property + " is: " + value);

                // ignore the value if it's null
                if (StringUtils.isNotBlank(value) || !StringUtils.equalsIgnoreCase(value, "null")) {
                    newParams.put(property, value);
                } else if (StringUtils.isBlank(value) && property.equals(minQueryTermLengthKeyName)) {
                    newParams.put(property, "0");
                } else if (StringUtils.isBlank(value) && property.equals(maxInventoryResponseKeyName)) {
                    newParams.put(property, "0");
                } else if (StringUtils.isBlank(value) && property.equals(maxSearchResponseKeyName)) {
                    newParams.put(property, "0");
                }
            }

            // Determine the schema location
            if (newParams.containsKey(schemaLocationKeyName)) {
                schemaLocation = (String) newParams.get(schemaLocationKeyName);
            }

            // Get the resourceName
            String resourceName = null;
            if (newParams.containsKey(resourceNameKeyName)) {
                resourceName = (String) newParams.get(resourceNameKeyName);
            }

            String mappingFile = getMappingFile(schemaLocation, directory, resourceName);

            // Determine the protocol
            protocol = getProtocol(schemaLocation);

            // Determine the count
            if (newParams.containsKey(recordCountKeyName)) {
                recordCount = (String) newParams.get(recordCountKeyName);
            }

            // ensure resource relates to a recognized conceptualSchema
            boolean recognizedConceptualSchema = false;
            if (newParams.containsKey(conceptualSchemaKeyName)) {
                conceptualSchema = (String) newParams.get(conceptualSchemaKeyName);
                if (StringUtils.isNotBlank(conceptualSchema)) {
                    recognizedConceptualSchema = conceptualSchemaWhitelist.contains(conceptualSchema);
                }
            }

            // only proceed with biodatasource creation if we have a resourceName
            if (StringUtils.isNotBlank(StringUtils.trimToNull(resourceName)) && recognizedConceptualSchema) {

                // Get location where we'll save the contact file
                String validatedResourceName = fileUtils.validateDirectoryName(resourceName);

                // create new directory if necessary
                File resourceDirectory = new File(directory, validatedResourceName);
                if (!resourceDirectory.exists()) {
                    log.debug("Creating new directory: " + resourceDirectory.getAbsolutePath());
                    resourceDirectory.mkdirs(); // including parents
                }

                // delete pre-existing contact file
                fileUtils.prepareDirectory(resourceDirectory.getAbsolutePath(), Constants.CONTACT_FILENAME);

                // create new contact file
                File newContactsFile = new File(resourceDirectory + "/" + Constants.CONTACT_FILENAME
                        + Constants.TEXT_FILENAME_EXTENSION);
                newContactsFile.createNewFile();

                // create bufferedWriter on contact file
                BufferedWriter newContactsBW = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(newContactsFile, true), "UTF8"));

                // write header line
                fileUtils.writeValuesToFile(newContactsBW, contactPropertiesList);

                // Move over contacts as far as position of current cursor
                while (contactLineNumber <= resourceLineNumber && StringUtils.isNotBlank(contactLine)) {

                    // retrieve all values, minus line number
                    List<String> contactValues = retrieveStringListFromLine(contactLine);

                    // write values to file
                    fileUtils.writeValuesToFile(newContactsBW, contactValues);

                    // move to next line
                    contactLine = fileUtils.readUTFLine(contactsRaf);
                    if (StringUtils.isNotBlank(contactLine)) {
                        int lineNumber = Integer.valueOf(fileUtils.getDelimitedPart(contactLine, "\t", 0));
                        if (lineNumber > contactLineNumber) {
                            contactLineNumber = lineNumber;
                        }
                    }
                }

                // close BW
                newContactsBW.close();

                // log having written the files so that they appear in the console
                log.info("Writing to file: " + newContactsFile.getAbsolutePath());

                // Construct the new BioDatasource
                createOrUpdateBioDatasource(name, url, resourceName, recordCount, uddiKey, newParams,
                        schemaLocation, mappingFile, protocol, (String) params.get("directory"));
            } else if (StringUtils.isBlank(StringUtils.trimToNull(resourceName))) {
                log.error("error.issueMetadata.noName");
            } else if (!recognizedConceptualSchema) {
                log.error("conceptualSchema (" + conceptualSchema + ") was not recognized for resource="
                        + resourceName + " therefore NO BioDatasource will be created");
            }
        }
    } catch (IOException e) {
        log.error("An IOException occurred during issueMetadata(): " + e.getMessage(), e);
    } finally {
        try {
            if (contactsRaf != null) {
                contactsRaf.close();
            }
        } catch (IOException e) {
            log.error("digirmetadatahandler.error.issueMetadata.closingCursors");
        }
        try {
            if (resourcesRaf != null) {
                resourcesRaf.close();
            }
        } catch (IOException e) {
            log.error("digirmetadatahandler.error.issueMetadata.closingCursors");
        }
    }
    log.info("end.issueMetadata");
}

From source file:cern.acet.tracing.input.file.tailer.PositionTailer.java

/**
 * Follows changes in the file, calling the PositionTailerListener's handle method for each new line.
 *//*from ww w  . j av a  2  s . co  m*/
public void run() {
    RandomAccessFile reader = null;
    try {
        long last = 0; // The last time the file was checked for changes
        long position = 0; // position within the file
        // Open the file
        while (run && reader == null) {
            try {
                reader = new RandomAccessFile(file, RAF_MODE);
            } catch (FileNotFoundException e) {
                listener.fileNotFound();
            }

            if (reader == null) {
                try {
                    Thread.sleep(delayMillis);
                } catch (InterruptedException e) {
                }
            } else {
                // The current position in the file
                position = startingPosition == null ? file.length() : startingPosition;
                last = System.currentTimeMillis();
                reader.seek(position);
            }
        }

        while (run) {

            boolean newer = FileUtils.isFileNewer(file, last); // IO-279, must be done first

            // Check the file length to see if it was rotated
            long length = file.length();

            if (length < position) {

                // File was rotated
                listener.fileRotated();

                // Reopen the reader after rotation
                try {
                    // Ensure that the old file is closed iff we re-open it successfully
                    RandomAccessFile save = reader;
                    reader = new RandomAccessFile(file, RAF_MODE);
                    position = 0;
                    // close old file explicitly rather than relying on GC picking up previous RAF
                    IOUtils.closeQuietly(save);
                } catch (FileNotFoundException e) {
                    // in this case we continue to use the previous reader and position values
                    listener.fileNotFound();
                }
                continue;
            } else {

                // File was not rotated

                // See if the file needs to be read again
                if (length > position) {

                    // The file has more content than it did last time
                    position = readLines(reader);
                    last = System.currentTimeMillis();

                } else if (newer) {

                    /*
                     * This can happen if the file is truncated or overwritten with the exact same length of
                     * information. In cases like this, the file position needs to be reset
                     */
                    position = 0;
                    reader.seek(position); // cannot be null here
                    // Now we can read new lines
                    position = readLines(reader);
                    last = System.currentTimeMillis();
                }
            }
            if (reOpen) {
                IOUtils.closeQuietly(reader);
            }
            try {
                Thread.sleep(delayMillis);
            } catch (InterruptedException e) {
            }
            if (run && reOpen) {
                reader = new RandomAccessFile(file, RAF_MODE);
                reader.seek(position);
            }
        }

    } catch (Exception e) {

        listener.handle(e);

    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:middleware.LogTailer.java

@Override
public void run() {
    RandomAccessFile reader = null;
    try {/* ww w  . ja  v  a  2  s .co  m*/
        long last = 0; // The last time the file was checked for changes
        long position = 0; // position within the file
        // Open the file
        while (run && reader == null) {
            try {
                reader = new RandomAccessFile(file, RAF_MODE);
            } catch (FileNotFoundException e) {
                listener.fileNotFound();
            }

            if (reader == null) {
                try {
                    Thread.sleep(delayMillis);
                } catch (InterruptedException e) {
                }
            } else {
                // The current position in the file
                //               position = (startOffset > file.length()) ? file.length() : startOffset;
                if (startOffset == -1) {
                    position = file.length();
                } else {
                    position = startOffset;
                }
                last = System.currentTimeMillis();
                reader.seek(position);
            }
        }

        while (run) {

            boolean newer = FileUtils.isFileNewer(file, last); // IO-279, must be done first

            // Check the file length to see if it was rotated
            long length = file.length();

            if (length < position) {

                // File was rotated
                listener.fileRotated();

                // Reopen the reader after rotation
                try {
                    // Ensure that the old file is closed iff we re-open it successfully
                    RandomAccessFile save = reader;
                    reader = new RandomAccessFile(file, RAF_MODE);
                    position = 0;
                    // close old file explicitly rather than relying on GC picking up previous RAF
                    IOUtils.closeQuietly(save);
                } catch (FileNotFoundException e) {
                    // in this case we continue to use the previous reader and position values
                    listener.fileNotFound();
                }
                continue;
            } else {

                // File was not rotated

                // See if the file needs to be read again
                if (length > position) {

                    // The file has more content than it did last time
                    position = readLines(reader);
                    last = System.currentTimeMillis();

                } else if (newer) {

                    /*
                     * This can happen if the file is truncated or overwritten with the exact same length of
                     * information. In cases like this, the file position needs to be reset
                     */
                    position = 0;
                    reader.seek(position); // cannot be null here

                    // Now we can read new lines
                    position = readLines(reader);
                    last = System.currentTimeMillis();
                } else {
                    Thread.sleep(DEFAULT_DELAY_MILLIS);
                }
            }
        }

    } catch (Exception e) {

        listener.handle(e);

    } finally {
        IOUtils.closeQuietly(reader);
    }
}