Example usage for java.io RandomAccessFile RandomAccessFile

List of usage examples for java.io RandomAccessFile RandomAccessFile

Introduction

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

Prototype

public RandomAccessFile(File file, String mode) throws FileNotFoundException 

Source Link

Document

Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

Usage

From source file:com.bittorrent.mpetazzoni.client.storage.FileStorage.java

public FileStorage(File file, long offset, long size) throws IOException {
    this.target = file;
    this.offset = offset;
    this.size = size;

    this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);

    if (this.partial.exists()) {
        logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath());
        this.current = this.partial;
    } else if (!this.target.exists()) {
        logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath());
        this.current = this.partial;
    } else {//from  w ww  .j  a v a 2  s.  c  o m
        logger.debug("Using existing file {}.", this.target.getAbsolutePath());
        this.current = this.target;
    }

    this.raf = new RandomAccessFile(this.current, "rw");

    // Set the file length to the appropriate size, eventually truncating
    // or extending the file if it already exists with a different size.
    this.raf.setLength(this.size);

    this.channel = raf.getChannel();
    logger.info("Initialized byte storage file at {} " + "({}+{} byte(s)).",
            new Object[] { this.current.getAbsolutePath(), this.offset, this.size, });
}

From source file:at.tuwien.minimee.util.TopParser.java

public void parse() {

    try {/* ww w .j a va  2s .  c  o m*/

        input = new RandomAccessFile(file, "r");

        try {

            monitoredPid = findPid();

            // couldn't determine PID
            if (monitoredPid == null) {
                return;
            }

            String line = null;
            while ((line = input.readLine()) != null) {
                parseLine(line);
            }

        } finally {
            input.close();
        }

        // list.debugToConsole();

    } catch (Exception e) {
        log.error(e);
    }
}

From source file:fm.last.commons.io.LastFileUtils.java

/**
 * Reads the last bytes from the end of the passed file as a String.
 * //from w  w w  .  ja v a 2s .  co  m
 * @param file File to read from.
 * @param bytes Number of bytes from end of file to read.
 * @return The end content of the file as a String.
 * @throws IOException If the file could not be opened or read.
 */
public static String tail(File file, long bytes) throws IOException {
    RandomAccessFile raFile = null;
    StringBuffer tail = new StringBuffer();
    try {
        raFile = new RandomAccessFile(file, "r");
        long length = raFile.length();
        if (bytes >= length) {
            return FileUtils.readFileToString(file);
        } else {
            raFile.seek(length - bytes);
            tail = new StringBuffer((int) bytes);
            String line = raFile.readLine();
            while (line != null) {
                tail.append(line);
                line = raFile.readLine();
                if (line != null) { // there is another line coming, so add line break
                    tail.append("\n");
                }
            }
        }
    } finally {
        LastIoUtils.closeQuietly(raFile);
    }
    return tail.toString();
}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

@Deprecated
public void releaseLocks() {
    l.trace("Trying to check file locks ");
    try {/*from  ww w .j  a va 2s .c om*/
        Collection c = FileUtils.listFiles(new File(Shared.workingDirectory), null, true);
        Object[] arr = c.toArray();
        for (int i = 0; i < arr.length; i++) {
            l.trace("Trying lock for: " + ((File) arr[i]).getAbsolutePath());
            // Get a file channel for the file
            File file = ((File) arr[i]);
            FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
            // Use the file channel to create a lock on the file.
            // This method blocks until it can retrieve the lock.
            //FileLock lock = channel.lock();
            // Try acquiring the lock without blocking. This method returns
            // null or throws an exception if the file is already locked.
            FileLock lock = null;
            try {
                lock = channel.lock();
            } catch (OverlappingFileLockException ex) {
                l.trace("Lock already exists", ex);
            }
            if (lock == null) {
                l.trace("Lock failed - someone else holds lock");
            } else {
                l.trace("Lock shared: " + lock.isShared() + " Lock valid: " + lock.isValid());
                lock.release();
                l.trace("Lock release OK");
                try {
                    if (!file.delete()) {
                        throw new IOException();
                    }
                } catch (Exception e) {
                    l.trace("Delete failed", e);
                }
            }
        }
        //Thread.sleep(25000);

    } catch (Exception e) {
        // File is already locked in this thread or virtual machine
        l.trace("File lock problem", e);
    }
}

From source file:com.owncloud.android.lib.resources.files.ChunkedUploadRemoteFileOperation.java

@Override
protected int uploadFile(OwnCloudClient client) throws HttpException, IOException {
    int status = -1;

    FileChannel channel = null;//w  w w . jav a  2 s  . c  o  m
    RandomAccessFile raf = null;
    try {
        File file = new File(mLocalPath);
        raf = new RandomAccessFile(file, "r");
        channel = raf.getChannel();
        mEntity = new ChunkFromFileChannelRequestEntity(channel, mMimeType, CHUNK_SIZE, file);
        //((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(getDataTransferListeners());
        synchronized (mDataTransferListeners) {
            ((ProgressiveDataTransferer) mEntity).addDatatransferProgressListeners(mDataTransferListeners);
        }

        long offset = 0;
        String uriPrefix = client.getWebdavUri() + WebdavUtils.encodePath(mRemotePath) + "-chunking-"
                + Math.abs((new Random()).nextInt(9000) + 1000) + "-";
        long chunkCount = (long) Math.ceil((double) file.length() / CHUNK_SIZE);
        for (int chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++, offset += CHUNK_SIZE) {
            if (mPutMethod != null) {
                mPutMethod.releaseConnection(); // let the connection available for other methods
            }
            mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex);
            mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER);
            ((ChunkFromFileChannelRequestEntity) mEntity).setOffset(offset);
            mPutMethod.setRequestEntity(mEntity);
            status = client.executeMethod(mPutMethod);
            client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
            Log_OC.d(TAG, "Upload of " + mLocalPath + " to " + mRemotePath + ", chunk index " + chunkIndex
                    + ", count " + chunkCount + ", HTTP result status " + status);
            if (!isSuccess(status))
                break;
        }

    } finally {
        if (channel != null)
            channel.close();
        if (raf != null)
            raf.close();
        if (mPutMethod != null)
            mPutMethod.releaseConnection(); // let the connection available for other methods
    }
    return status;
}

From source file:com.taobao.common.tfs.impl.LocalKey.java

public void init(String key, long serverId) throws TfsException {
    TfsUtil.createDirectory(TfsConstant.TFS_TMP_PATH, TfsConstant.TFS_TMP_PATH_MODE);
    clear();/*from   w ww .ja  v a  2 s.com*/

    try {
        localKeyName = convertName(key, serverId);

        fileOp = new RandomAccessFile(localKeyName, "rw");

        if (fileOp.length() == 0) {
            log.info("create new localkey file: " + localKeyName);
        } else if (fileOp.length() < SegmentHead.size()) {
            log.warn("localkey file is invaid, ignore: " + localKeyName);
        } else {
            log.info("localkey file exist, load: " + localKeyName);
            try {
                load();
            } catch (Exception e) {
                log.warn("load localkey fail, file is invalid, create new localkey file. " + localKeyName, e);
                clear();
            }
        }
        // init gc file with localkey file name
        gcFile.init(localKeyName.substring(TfsConstant.TFS_TMP_PATH.length()));
    } catch (Exception e) {
        throw new TfsException("init local key fail: " + localKeyName, e);
    }
}

From source file:RandomRead.java

/** Constructor: save filename, construct RandomAccessFile */
public RandomRead(String fname) throws IOException {
    fileName = fname;//from w w w  . j  a  v a 2  s  .c o m
    seeker = new RandomAccessFile(fname, "r");
}

From source file:middleware.LogTailer.java

@Override
public void run() {
    RandomAccessFile reader = null;
    try {//from w w w . j a  v a2 s . c o 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);
    }
}

From source file:com.turn.ttorrent.client.TorrentByteStorage.java

public TorrentByteStorage(File file, long size) throws IOException {
    this.target = file;
    this.size = size;

    this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);

    if (this.partial.exists()) {
        logger.info("Partial download found at " + this.partial.getAbsolutePath() + ". Continuing...");
        this.current = this.partial;
    } else if (!this.target.exists()) {
        logger.info("Downloading new file to " + this.partial.getAbsolutePath() + "...");
        this.current = this.partial;
    } else {//from   ww  w  .  j ava2  s. c o  m
        logger.info("Using existing file " + this.target.getAbsolutePath() + ".");
        this.current = this.target;
    }

    this.raf = new RandomAccessFile(this.current, "rw");

    // Set the file length to the appropriate size, eventually truncating
    // or extending the file if it already exists with a different size.
    this.raf.setLength(this.size);

    this.channel = raf.getChannel();
    logger.debug("Initialized torrent byte storage at " + this.current.getAbsolutePath() + ".");
}

From source file:com.l2jfree.gameserver.cache.CrestCache.java

public synchronized void reload() {
    FileFilter filter = new BmpFilter();

    File dir = new File(Config.DATAPACK_ROOT, "data/crests/");

    File[] files = dir.listFiles(filter);
    if (files == null)
        files = new File[0];
    byte[] content;

    _loadedFiles = 0;// w w w . j a  va2 s .  co m
    _bytesBuffLen = 0;

    _cachePledge.clear();
    _cachePledgeLarge.clear();
    _cacheAlly.clear();

    for (File file : files) {
        RandomAccessFile f = null;
        try {
            f = new RandomAccessFile(file, "r");
            content = new byte[(int) f.length()];
            f.readFully(content);

            if (file.getName().startsWith("Crest_Large_")) {
                _cachePledgeLarge.put(
                        Integer.valueOf(file.getName().substring(12, file.getName().length() - 4)), content);
            } else if (file.getName().startsWith("Crest_")) {
                _cachePledge.put(Integer.valueOf(file.getName().substring(6, file.getName().length() - 4)),
                        content);
            } else if (file.getName().startsWith("AllyCrest_")) {
                _cacheAlly.put(Integer.valueOf(file.getName().substring(10, file.getName().length() - 4)),
                        content);
            }
            _loadedFiles++;
            _bytesBuffLen += content.length;
        } catch (Exception e) {
            _log.warn("Problem with loading crest bmp file: " + file, e);
        } finally {
            try {
                if (f != null)
                    f.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    _log.info(this);
}