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.sqlite.multiread.java

public void run() {
    newSqLiteAdapter.openToRead();/*w ww  .  ja  v  a2 s.c  om*/
    long seconds1 = 0;
    long seconds2 = 0;
    Cursor cur = null;
    Transactions transactions = new Transactions();
    ArrayList<Long> array = new ArrayList<Long>();
    for (int i = 0; i < 10; i++) {
        seconds1 = System.currentTimeMillis();
        //cur = newSqLiteAdapter.queueAll("dammyTable", false, false, false,
        //         false, false, false, true, threadNum);
        seconds2 = System.currentTimeMillis();
        array.add(seconds2 - seconds1);
    }
    //   newSqLiteAdapter.close();
    FileOutputStream fos = null;
    try {
        byte[] data = new String("\nTotal time: " + transactions.average_time(array) / 8 + "ms  Thread Id: "
                + currentThread().getId() + " I Have read " + cur.getCount()).getBytes();

        File file = new File(Environment.getExternalStorageDirectory() + "/Aaa/", "threadsResults.txt");

        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        FileLock lock = channel.lock();

        try {
            lock = channel.tryLock();
        } catch (OverlappingFileLockException e) {

        }

        fos = new FileOutputStream(file, true);
        fos.write(data);

        fos.flush();

        lock.release();
        channel.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.java

@Override
protected void processFiltered(File file, List<String> lines) {
    // Cannot use lines as the line separators have been removed!
    try {/*  ww w . j  av  a2s  . c om*/
        final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        boolean threw = true;
        try {
            if (!endsWithNewline(randomAccessFile)) {
                log(0, MSG_KEY_NO_NEWLINE_EOF, file.getPath());
            }
            threw = false;
        } finally {
            Closeables.close(randomAccessFile, threw);
        }
    } catch (final IOException ignored) {
        log(0, MSG_KEY_UNABLE_OPEN, file.getPath());
    }
}

From source file:dk.statsbiblioteket.hadoop.archeaderextractor.ARCHeaderExtractor.java

private static Map<Long, String> parse(File arcFile) throws IOException {
    Map<Long, String> headers = new HashMap<Long, String>();

    /*//from w w  w .  j av  a  2  s  .  c o m
    String lastModifiedString = String.valueOf(arcFile.lastModified());
    headers.put((long) 1, lastModifiedString);
    return headers;
    */

    /*  extract the time stamp from the file name of the ARC file
    The time stamp is the third element of the file name when split on "-".
     */

    String timeStamp = arcFile.getName().split("-")[2];

    RandomAccessFile raf;
    RandomAccessFileInputStream rafin;
    ByteCountingPushBackInputStream pbin;

    ArcReader arcReader = null;
    ArcRecordBase arcRecord;
    UriProfile uriProfile = UriProfile.RFC3986;

    boolean bBlockDigestEnabled = true;
    boolean bPayloadDigestEnabled = true;
    int recordHeaderMaxSize = 8192;
    int payloadHeaderMaxSize = 32768;

    raf = new RandomAccessFile(arcFile, "r");
    rafin = new RandomAccessFileInputStream(raf);
    pbin = new ByteCountingPushBackInputStream(new BufferedInputStream(rafin, 8192), 16);

    if (ArcReaderFactory.isArcFile(pbin)) {
        arcReader = ArcReaderFactory.getReaderUncompressed(pbin);
        arcReader.setUriProfile(uriProfile);
        arcReader.setBlockDigestEnabled(bBlockDigestEnabled);
        arcReader.setPayloadDigestEnabled(bPayloadDigestEnabled);
        arcReader.setRecordHeaderMaxSize(recordHeaderMaxSize);
        arcReader.setPayloadHeaderMaxSize(payloadHeaderMaxSize);

        while ((arcRecord = arcReader.getNextRecord()) != null) {
            headers.put(arcRecord.getStartOffset(), extractHeader(arcRecord, timeStamp));
        }
        arcReader.close();
    } else {
        System.err.println("Input file is not an ARC file");
    }

    if (arcReader != null) {
        arcReader.close();
    }
    pbin.close();
    raf.close();

    return headers;

}

From source file:eu.delving.sip.files.ReportFile.java

public ReportFile(File reportFile, File reportIndexFile, File invalidFile, File linkFile, DataSet dataSet,
        String prefix) throws IOException {
    this.reportFile = reportFile;
    this.reportAccess = new RandomAccessFile(this.reportFile, "r");
    this.reportIndexAccess = new RandomAccessFile(reportIndexFile, "r");
    this.linkFile = new LinkFile(linkFile, dataSet, prefix);
    this.dataSet = dataSet;
    this.prefix = prefix;
    int recordCount = (int) (reportIndexAccess.length() / LONG_SIZE);
    recs = new ArrayList<Rec>(recordCount);
    for (int walk = 0; walk < recordCount; walk++)
        recs.add(new Rec(walk));
    DataInputStream invalidIn = new DataInputStream(new FileInputStream(invalidFile));
    int invalidCount = invalidIn.readInt();
    invalidRecs = new ArrayList<Rec>(invalidCount);
    for (int walk = 0; walk < invalidCount; walk++) {
        int recordNumber = invalidIn.readInt();
        invalidRecs.add(recs.get(recordNumber));
    }/* w  ww  . j av a2 s . c  o m*/
    invalidIn.close();
}

From source file:mobac.program.atlascreators.impl.rmp.RmpWriter.java

/**
 * @param imageName//from  www  . j  a v a 2 s .  com
 * @param layerCount
 *            projected number of layers that will be written to this rmp file
 * @param rmpFile
 * @throws IOException
 * @throws InterruptedException
 */
public RmpWriter(String imageName, int layerCount, File rmpFile) throws IOException, InterruptedException {
    this.rmpFile = rmpFile;
    // We only use one A00 entry per map/layer - therefore we can
    // pre-calculate the number of entries:
    // RmpIni + (TLM & A00) per layer + Bmp2Bit + Bmp4bit
    this.projectedEntryCount = (3 + (2 * layerCount));
    if (rmpFile.exists())
        Utilities.deleteFile(rmpFile);
    log.debug("Writing data to " + rmpFile.getAbsolutePath());
    rmpOutputFile = new RandomAccessFile(rmpFile, "rw");
    // Calculate offset to the directory end
    int directoryEndOffset = projectedEntryCount * 24 + 10;
    rmpOutputFile.seek(directoryEndOffset);
    entryOut = new ChecksumOutputStream(new RandomAccessFileOutputStream(rmpOutputFile));
    /* --- Write the directory-end marker --- */
    RmpTools.writeFixedString(entryOut, "MAGELLAN", 30);

    RmpIni rmpIni = new RmpIni(imageName, layerCount);

    /* --- Create packer and fill it with content --- */
    writeFileEntry(rmpIni);
}

From source file:com.linkedin.pinot.core.indexsegment.utils.GenericRowColumnDataFileReader.java

/**
 *
 * @param dataFile//  ww  w.  j  a va2 s.co m
 * @param rows
 * @param cols
 * @param columnSizes in bytes
 * @throws IOException
 */
public GenericRowColumnDataFileReader(File dataFile, int rows, int cols, int[] columnSizes, boolean isMmap)
        throws IOException {
    this.rows = rows;
    this.cols = cols;
    this.columnSizes = columnSizes;
    colOffSets = new int[columnSizes.length];
    for (int i = 0; i < columnSizes.length; i++) {
        if (i == 0) {
            colOffSets[i] = 0;
        } else {
            colOffSets[i] = colOffSets[i - 1] + columnSizes[i - 1];
        }
        rowSize += columnSizes[i];
    }
    file = new RandomAccessFile(dataFile, "rw");
    long totalSize = rowSize * rows;
    if (isMmap)
        byteBuffer = MmapUtils.mmapFile(file, FileChannel.MapMode.READ_ONLY, 0, totalSize, dataFile,
                this.getClass().getSimpleName() + " byteBuffer");
    else {
        byteBuffer = MmapUtils.allocateDirectByteBuffer((int) totalSize, dataFile,
                this.getClass().getSimpleName() + " byteBuffer");
        file.getChannel().read(byteBuffer);
    }
}

From source file:com.cerema.cloud2.lib.resources.files.ChunkedUploadRemoteFileOperation.java

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

    FileChannel channel = null;//from w w  w  .  j  av  a 2  s .c  om
    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);
        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 totalLength = file.length();
        long chunkCount = (long) Math.ceil((double) totalLength / CHUNK_SIZE);
        String chunkSizeStr = String.valueOf(CHUNK_SIZE);
        String totalLengthStr = String.valueOf(file.length());
        for (int chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++, offset += CHUNK_SIZE) {
            if (chunkIndex == chunkCount - 1) {
                chunkSizeStr = String.valueOf(CHUNK_SIZE * chunkCount - totalLength);
            }
            if (mPutMethod != null) {
                mPutMethod.releaseConnection(); // let the connection available
                                                // for other methods
            }
            mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex);
            if (mRequiredEtag != null && mRequiredEtag.length() > 0) {
                mPutMethod.addRequestHeader(IF_MATCH_HEADER, "\"" + mRequiredEtag + "\"");
            }
            mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER);
            mPutMethod.addRequestHeader(OC_CHUNK_SIZE_HEADER, chunkSizeStr);
            mPutMethod.addRequestHeader(OC_TOTAL_LENGTH_HEADER, totalLengthStr);
            ((ChunkFromFileChannelRequestEntity) mEntity).setOffset(offset);
            mPutMethod.setRequestEntity(mEntity);
            if (mCancellationRequested.get()) {
                mPutMethod.abort();
                // next method will throw an exception
            }
            status = client.executeMethod(mPutMethod);

            if (status == 400) {
                InvalidCharacterExceptionParser xmlParser = new InvalidCharacterExceptionParser();
                InputStream is = new ByteArrayInputStream(mPutMethod.getResponseBodyAsString().getBytes());
                try {
                    mForbiddenCharsInServer = xmlParser.parseXMLResponse(is);

                } catch (Exception e) {
                    mForbiddenCharsInServer = false;
                    Log_OC.e(TAG, "Exception reading exception from server", e);
                }
            }

            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:name.martingeisse.stackd.server.section.storage.FolderBasedSectionStorage.java

/**
 * Constructor./* w  w w .j a  v a 2 s.com*/
 * @param clusterSize the cluster-size of sections
 * @param storageFolder the folder that contains world storage files
 */
public FolderBasedSectionStorage(final ClusterSize clusterSize, final File storageFolder) {
    super(clusterSize);
    this.storageFolder = storageFolder;
    this.fileHandleCache = CacheBuilder.newBuilder().maximumSize(100)
            .removalListener(new RemovalListener<SectionId, RandomAccessFile>() {
                @Override
                public void onRemoval(RemovalNotification<SectionId, RandomAccessFile> notification) {
                    try {
                        notification.getValue().close();
                    } catch (IOException e) {
                    }
                }
            }).build(new CacheLoader<SectionId, RandomAccessFile>() {
                @Override
                public RandomAccessFile load(SectionId superSectionId) throws Exception {
                    File file = getSectionFile(superSectionId);

                    // create an empty file if there is none yet
                    if (!file.exists()) {
                        final FileOutputStream fileOutputStream = new FileOutputStream(file);
                        try {
                            final byte[] emptyToc = new byte[16 * 16 * 16 * 3 * 4];
                            fileOutputStream.write(emptyToc);
                        } finally {
                            fileOutputStream.close();
                        }
                    }

                    return new RandomAccessFile(file, "rw");
                }
            });
}

From source file:net.minecraftforge.fml.repackage.com.nothome.delta.GDiffPatcher.java

/**
 * Patches to an output file.//w  w  w  . j a  va2 s .  c  om
 */
public void patch(File sourceFile, File patchFile, File outputFile) throws IOException {
    RandomAccessFileSeekableSource source = new RandomAccessFileSeekableSource(
            new RandomAccessFile(sourceFile, "r"));
    InputStream patch = null;
    OutputStream output = null;
    try {
        patch = new FileInputStream(patchFile);
        output = new FileOutputStream(outputFile);
        patch(source, patch, output);
    } finally {
        IOUtils.closeQuietly(source);
        IOUtils.closeQuietly(patch);
        IOUtils.closeQuietly(output);
    }
}

From source file:eu.trentorise.smartcampus.feedback.test.TestFeedbackManagers.java

private byte[] readTestFile() throws IOException {
    RandomAccessFile f = new RandomAccessFile("src/test/resources/android.jpg", "r");
    byte[] b = new byte[(int) f.length()];
    f.read(b);//  w w w.  j  a  v  a2  s . co m
    f.close();
    return b;
}