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.aoyetech.fee.commons.utils.FileUtils.java

public static String getFileContent(final File tFile)
        throws IOException, FileNotFoundException, UnsupportedEncodingException {
    if (!tFile.isFile()) {
        throw new IOException("?");
    }//  w  w w .  ja  va  2 s.com
    final RandomAccessFile file = new RandomAccessFile(tFile, "r");
    final long fileSize = file.length();
    final byte[] bytes = new byte[(int) fileSize];
    long readLength = 0L;
    while (readLength < fileSize) {
        final int onceLength = file.read(bytes, (int) readLength, (int) (fileSize - readLength));
        if (onceLength > 0) {
            readLength += onceLength;
        } else {
            break;
        }
    }

    IOUtils.closeQuietly(file);
    return new String(bytes, Constants.ENCODE);
}

From source file:io.pivotal.kr.load_gen.LineReader.java

public LineReader(int bufSize, String path) throws IOException {
    this.file = new RandomAccessFile(path, "r");
    this.reader = new BufferedInputStream(new FileInputStream(file.getFD()));
    this.cbuf = new byte[bufSize];
    this.rbuf = new byte[bufSize];
    this.offset = 0L;
    this.bufSize = bufSize;
    this.rbufIdx = 0;
}

From source file:com.linkedin.pinot.core.io.writer.impl.v1.FixedByteMultiValueWriter.java

public FixedByteMultiValueWriter(File file, int numDocs, int totalNumValues, int columnSizeInBytes)
        throws Exception {
    // there will be two sections header and data
    // header will contain N lines, each line corresponding to the
    int headerSize = numDocs * SIZE_OF_INT * NUM_COLS_IN_HEADER;
    int dataSize = totalNumValues * columnSizeInBytes;
    int totalSize = headerSize + dataSize;
    raf = new RandomAccessFile(file, "rw");
    headerBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, headerSize, file,
            this.getClass().getSimpleName() + " headerBuffer");
    dataBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, headerSize, dataSize, file,
            this.getClass().getSimpleName() + " dataBuffer");
    headerWriter = new FixedByteSingleValueMultiColWriter(headerBuffer, numDocs, 2,
            new int[] { SIZE_OF_INT, SIZE_OF_INT });
    headerReader = new FixedByteSingleValueMultiColReader(headerBuffer, numDocs, 2,
            new int[] { SIZE_OF_INT, SIZE_OF_INT });

    dataWriter = new FixedByteSingleValueMultiColWriter(dataBuffer, totalNumValues, 1,
            new int[] { columnSizeInBytes });

}

From source file:com.asakusafw.runtime.util.lock.LocalFileLockProvider.java

@Override
public LocalFileLockObject<T> tryLock(T target) throws IOException {
    if (baseDirectory.mkdirs() == false && baseDirectory.isDirectory() == false) {
        throw new IOException(MessageFormat.format("Failed to create lock directory: {0}", baseDirectory));
    }/*from   w  w w. j a va2  s  . c o  m*/
    String fileName = String.format("%08x.lck", target == null ? -1 : target.hashCode()); //$NON-NLS-1$
    File lockFile = new File(baseDirectory, fileName);
    RandomAccessFile fd = new RandomAccessFile(lockFile, "rw"); //$NON-NLS-1$
    boolean success = false;
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug(MessageFormat.format("Start to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                    target, lockFile));
        }
        FileLock lockEntity = getLock(target, lockFile, fd);
        if (lockEntity == null) {
            return null;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Finished to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                        target, lockFile));
            }
            try {
                fd.seek(0L);
                fd.setLength(0L);
                fd.write(String.valueOf(target).getBytes(ENCODING));
                success = true;
                return new LocalFileLockObject<>(target, lockFile, fd, lockEntity);
            } finally {
                if (success == false) {
                    lockEntity.release();
                }
            }
        }
    } finally {
        if (success == false) {
            fd.close();
        }
    }
}

From source file:com.linkedin.pinot.core.index.writer.impl.FixedByteWidthSingleColumnMultiValueWriter.java

public FixedByteWidthSingleColumnMultiValueWriter(File file, int numDocs, int totalNumValues,
        int columnSizeInBytes) throws Exception {
    // there will be two sections header and data
    // header will contain N lines, each line corresponding to the
    int headerSize = numDocs * SIZE_OF_INT * NUM_COLS_IN_HEADER;
    int dataSize = totalNumValues * columnSizeInBytes;
    int totalSize = headerSize + dataSize;
    raf = new RandomAccessFile(file, "rw");
    headerBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, headerSize, file,
            this.getClass().getSimpleName() + " headerBuffer");
    dataBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, headerSize, dataSize, file,
            this.getClass().getSimpleName() + " dataBuffer");
    headerWriter = new FixedByteWidthRowColDataFileWriter(headerBuffer, numDocs, 2,
            new int[] { SIZE_OF_INT, SIZE_OF_INT });
    headerReader = new FixedByteWidthRowColDataFileReader(headerBuffer, numDocs, 2,
            new int[] { SIZE_OF_INT, SIZE_OF_INT });

    dataWriter = new FixedByteWidthRowColDataFileWriter(dataBuffer, totalNumValues, 1,
            new int[] { columnSizeInBytes });

}

From source file:com.owncloud.android.operations.ChunkedUploadFileOperation.java

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

    FileChannel channel = null;/*from  ww w .ja  v a2  s . c o m*/
    RandomAccessFile raf = null;
    try {
        File file = new File(getStoragePath());
        raf = new RandomAccessFile(file, "r");
        channel = raf.getChannel();
        mEntity = new ChunkFromFileChannelRequestEntity(channel, getMimeType(), CHUNK_SIZE, file);
        ((ProgressiveDataTransferer) mEntity).addDatatransferProgressListeners(getDataTransferListeners());
        long offset = 0;
        String uriPrefix = client.getBaseUri() + WebdavUtils.encodePath(getRemotePath()) + "-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 " + getStoragePath() + " to " + getRemotePath() + ", 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:net.sf.zekr.common.resource.QuranText.java

/**
 * The private constructor, which loads the whole Quran text from file into memory (<code>quranText</code>
 * ).//  ww  w  . ja  va 2  s  .  c  o m
 * 
 * @param textType can be either UTHMANI_MODE or SIMPLE_MODE
 * @throws IOException
 */
protected QuranText(int textType) throws IOException {
    mode = textType;
    String qFile = ApplicationPath.SIMPLE_QURAN_TEXT_FILE;
    if (textType == UTHMANI_MODE) {
        qFile = ApplicationPath.UTHMANI_QURAN_TEXT_FILE;
    }

    RandomAccessFile raf = new RandomAccessFile(qFile, "r");
    byte[] buf = new byte[(int) raf.length()];
    raf.readFully(buf);
    rawText = new String(buf, config.getProps().getString("quran.text.encoding"));
    refineRawText();
    raf.close();
}

From source file:ja.centre.util.io.nio.MappedByteBufferWrapper.java

public MappedByteBufferWrapper(String fileName) throws IOException {
    Arguments.assertNotNull("fileName", fileName);

    Files.assertExists(fileName);

    LOG.info("Opening \"" + fileName + "\"...");
    this.fileName = fileName;

    try {/*from   w ww  .  j  av  a  2s.  co  m*/
        raf = new RandomAccessFile(fileName, "rw");

        try {
            initBuffer();
        } catch (IOException e) {
            LOG.info("Could not lock file \"" + fileName + "\". Switching to non-locking mode...");

            Files.closeQuietly(raf);
            raf = new RandomAccessFile(fileName, "r");
            initBuffer();
        }
    } catch (IOException e) {
        Files.closeQuietly(raf);
        throw e;
    }
}

From source file:com.liferay.faces.bridge.renderkit.primefaces.internal.PrimeFacesFileItem.java

public byte[] get() {

    byte[] bytes = null;

    try {// w w  w .  j  ava  2  s.  co  m
        File file = new File(uploadedFile.getAbsolutePath());

        if (file.exists()) {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
            bytes = new byte[(int) randomAccessFile.length()];
            randomAccessFile.readFully(bytes);
            randomAccessFile.close();
            file.delete();
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return bytes;
}

From source file:ListOfNumbers2.java

public void readList(String fileName) {
    String line = null;//from w  w w  .  j  a v a 2  s .co m
    try {
        RandomAccessFile raf = new RandomAccessFile(fileName, "r");
        while ((line = raf.readLine()) != null) {
            Integer i = new Integer(Integer.parseInt(line));
            System.out.println(i);
            victor.addElement(i);
        }
    } catch (FileNotFoundException fnf) {
        System.err.println("File: " + fileName + " not found.");
    } catch (IOException io) {
        System.err.println(io.toString());
    }
}