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.meidusa.venus.benchmark.FileLineData.java

@Override
public void init() throws InitialisationException {
    try {//from w ww  .  jav a  2  s  . c  om
        raf = new RandomAccessFile(file, "r");

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                closed = true;
                try {
                    raf.close();
                } catch (IOException e) {
                }
            }
        });
    } catch (IOException e) {
        throw new InitialisationException(e);
    }
}

From source file:dk.netarkivet.common.utils.cdx.BinSearch.java

/** Given a file in sorted order and a prefix to search for, return a
 * an iterable that will return the lines in the files that start with
 * the prefix, in order.  They will be read lazily from the file.
 *
 * If no matches are found, it will still return an iterable with no
 * entries.//from w  w w. j ava  2s .  com
 *
 * @param file A CDX file to search in.
 * @param prefix The line prefix to search for.
 * @return An Iterable object that will return the lines
 * matching the prefix in the file.
 */
public static Iterable<String> getLinesInFile(File file, String prefix) {
    try {
        RandomAccessFile in = null;
        try {
            in = new RandomAccessFile(file, "r");
            long matchingline = binSearch(in, prefix);
            if (matchingline == -1) {
                // Simple empty Iterable
                return Collections.emptyList();
            }
            long firstMatching = findFirstLine(in, prefix, matchingline);
            return new PrefixIterable(file, firstMatching, prefix);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    } catch (IOException e) {
        String message = "IOException reading file '" + file + "'";
        log.warn(message, e);
        throw new IOFailure(message, e);
    }
}

From source file:ape.CorruptFileCommand.java

/**
 * This method is the actual method used to corrupt data/file
 *//*from ww w .  j  a va  2  s  .c  o m*/
public boolean corrupt(String corruptAddress) throws IOException {
    FileInputStream fin;
    byte[] buf;
    int count;

    try {

        RandomAccessFile tmp = new RandomAccessFile(corruptAddress, "rw");
        tmp.seek(offset);

        if (size <= 0) {
            System.out.println("ERROR: The size parameter must be positive");
            Main.logger.info("ERROR: The size parameter must be positive");
            return false;
        }

        buf = new byte[size];

        count = 0;
        if ((count = tmp.read(buf, 0, size)) == -1) {
            System.out.println("The file chosen is smaller than the corruption size (" + size + " bytes)");
            Main.logger.info("The file chosen is smaller than the corruption size (" + size + " bytes)");
            return false;
        }

        for (int i = 0; i < count; i++) {
            buf[i] = 0x3;
        }

        tmp.seek(0);
        tmp.close();
    } catch (FileNotFoundException e1) {
        System.out.println("Cannot open the file on the path given");
        Main.logger.info("Cannot open the file on the path given");
        e1.printStackTrace();
        Main.logger.info(e1);
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(corruptAddress, "rw");
        try {
            raf.seek(offset);

            raf.write(buf, 0, count);
            raf.seek(0);
            raf.close();
        } catch (IOException e) {
            System.out.println("Corrupting file failed");
            Main.logger.info("Corrupting file failed");
            e.printStackTrace();
            Main.logger.info(e);
            return false;
        }

        return true;
    } catch (FileNotFoundException e1) {
        System.out.println("Cannot open the file on the path: " + corruptAddress);
        Main.logger.info("Cannot open the file on the path: " + corruptAddress);
        e1.printStackTrace();
        Main.logger.info(e1);
        return false;
    }
}

From source file:hoot.services.controllers.info.ErrorLog.java

static String generateExportLog() throws IOException {
    String fileId = UUID.randomUUID().toString();

    AboutResource about = new AboutResource();

    VersionInfo vInfo = about.getCoreVersionInfo();
    String data = System.lineSeparator() + "************ CORE VERSION INFO ***********"
            + System.lineSeparator();
    data += vInfo.toString();/*from w ww  .  j  a  va2 s  .  c o m*/

    CoreDetail cd = about.getCoreVersionDetail();
    data += System.lineSeparator() + "************ CORE ENVIRONMENT ***********" + System.lineSeparator();

    if (cd != null) {
        data += StringUtils.join(cd.getEnvironmentInfo(), System.lineSeparator());
    }

    data += System.lineSeparator() + "************ SERVICE VERSION INFO ***********" + System.lineSeparator();
    data += about.getServicesVersionInfo().toString();
    data += System.lineSeparator() + "************ CATALINA LOG ***********" + System.lineSeparator();

    // 5MB Max
    int maxSize = 5000000;

    String logStr = getErrorlog(maxSize);

    String outputPath = TEMP_OUTPUT_PATH + File.separator + fileId;
    try (RandomAccessFile raf = new RandomAccessFile(outputPath, "rw")) {
        raf.writeBytes(data + System.lineSeparator() + logStr);
        return outputPath;
    }
}

From source file:com.replaymod.replaystudio.launcher.ReverseLauncher.java

public void launch(CommandLine cmd) throws Exception {
    ZipFile file = new ZipFile(cmd.getArgs()[0]);
    ZipEntry entry = file.getEntry("recording.tmcpr");
    if (entry == null) {
        throw new IOException("Input file is not a valid replay file.");
    }/*from  w w w. j a  v a 2  s  . co m*/
    long size = entry.getSize();
    if (size == -1) {
        throw new IOException("Uncompressed size of recording.tmcpr not set.");
    }

    InputStream from = file.getInputStream(entry);
    RandomAccessFile to = new RandomAccessFile(cmd.getArgs()[1], "rw");

    to.setLength(size);
    int nRead;
    long pos = size;
    byte[] buffer = new byte[8192];

    long lastUpdate = -1;
    while (true) {
        long pct = 100 - pos * 100 / size;
        if (lastUpdate != pct) {
            System.out.print("Reversing " + size + " bytes... " + pct + "%\r");
            lastUpdate = pct;
        }
        int next = readInt(from);
        int length = readInt(from);
        if (next == -1 || length == -1) {
            break; // reached end of stream
        }
        // Increase buffer if necessary
        if (length + 8 > buffer.length) {
            buffer = new byte[length + 8];
        }
        buffer[0] = (byte) ((next >>> 24) & 0xFF);
        buffer[1] = (byte) ((next >>> 16) & 0xFF);
        buffer[2] = (byte) ((next >>> 8) & 0xFF);
        buffer[3] = (byte) (next & 0xFF);
        buffer[4] = (byte) ((length >>> 24) & 0xFF);
        buffer[5] = (byte) ((length >>> 16) & 0xFF);
        buffer[6] = (byte) ((length >>> 8) & 0xFF);
        buffer[7] = (byte) (length & 0xFF);

        nRead = 0;
        while (nRead < length) {
            nRead += from.read(buffer, 8 + nRead, length - nRead);
        }

        pos -= length + 8;
        to.seek(pos);
        to.write(buffer, 0, length + 8);
    }

    from.close();
    to.close();

    System.out.println("\nDone!");
}

From source file:com.sm.store.utils.FileStore.java

private void init() {
    try {//from   w w w .  ja v  a2 s  . c  o  m
        String index = "0";
        indexChannel = new RandomAccessFile(filename + index + ".ndx", "rw").getChannel();
        checkSignature(indexChannel);
        keyChannel = new RandomAccessFile(filename + index + ".key", "rw").getChannel();
        checkSignature(keyChannel);
        dataChannel = new RandomAccessFile(filename + index + ".data", "rw").getChannel();
        checkSignature(dataChannel);
        long length = indexChannel.size() - OFFSET;
        totalRecord = (int) (length / RECORD_SIZE);
        if (totalRecord > 0) {
            logger.info("Total record " + totalRecord + " move to eof and ready for append");
            reset();
        }
        dataOffset = dataChannel.size();
        keyOffset = keyChannel.size();
        logger.info("data " + dataOffset + "  index " + indexChannel.position() + " key " + keyOffset);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.qubole.rubix.core.RemoteReadRequestChain.java

public Integer call() throws IOException {
    Thread.currentThread().setName(threadName);
    checkState(isLocked, "Trying to execute Chain without locking");

    if (readRequests.size() == 0) {
        return 0;
    }//from  w w w . j  a  va2s .co  m

    RandomAccessFile localFile = null;
    FileChannel fc = null;

    try {
        localFile = new RandomAccessFile(localFilename, "rw");
        fc = localFile.getChannel();
        for (ReadRequest readRequest : readRequests) {
            log.debug(String.format("Executing ReadRequest: [%d, %d, %d, %d, %d]",
                    readRequest.getBackendReadStart(), readRequest.getBackendReadEnd(),
                    readRequest.getActualReadStart(), readRequest.getActualReadEnd(),
                    readRequest.getDestBufferOffset()));
            inputStream.seek(readRequest.backendReadStart);
            MappedByteBuffer mbuf = fc.map(FileChannel.MapMode.READ_WRITE, readRequest.backendReadStart,
                    readRequest.getBackendReadLength());
            log.debug(String.format("Mapped file from %d till length %d", readRequest.backendReadStart,
                    readRequest.getBackendReadLength()));
            /*
             * MappedByteBuffer does not provide backing byte array, so cannot write directly to it via FSDataOutputStream.read
             * Instead, download to normal destination buffer (+offset buffer to get block boundaries) and then copy to MappedByteBuffer
             */

            int prefixBufferLength = (int) (readRequest.getActualReadStart()
                    - readRequest.getBackendReadStart());
            int suffixBufferLength = (int) (readRequest.getBackendReadEnd() - readRequest.getActualReadEnd());
            log.debug(
                    String.format("PrefixLength: %d SuffixLength: %d", prefixBufferLength, suffixBufferLength));

            // TODO: use single byte buffer for all three streams
            /* TODO: also GC cost can be lowered by shared buffer pool, a small one.
            IOUtils.copyLarge method. A single 4kB byte buffer can be used to copy whole file
                    
              */
            if (prefixBufferLength > 0) {
                byte[] prefixBuffer = new byte[prefixBufferLength];
                log.debug(String.format("Trying to Read %d bytes into prefix buffer", prefixBufferLength));
                totalPrefixRead += readAndCopy(prefixBuffer, 0, mbuf, prefixBufferLength);
                log.debug(String.format("Read %d bytes into prefix buffer", prefixBufferLength));
            }
            log.debug(String.format("Trying to Read %d bytes into destination buffer",
                    readRequest.getActualReadLength()));
            int readBytes = readAndCopy(readRequest.getDestBuffer(), readRequest.destBufferOffset, mbuf,
                    readRequest.getActualReadLength());
            totalRequestedRead += readBytes;
            log.debug(String.format("Read %d bytes into destination buffer", readBytes));
            if (suffixBufferLength > 0) {
                // If already in reading actually required data we get a eof, then there should not have been a suffix request
                checkState(readBytes == readRequest.getActualReadLength(),
                        "Acutal read less than required, still requested for suffix");
                byte[] suffixBuffer = new byte[suffixBufferLength];
                log.debug(String.format("Trying to Read %d bytes into suffix buffer", suffixBufferLength));
                totalSuffixRead += readAndCopy(suffixBuffer, 0, mbuf, suffixBufferLength);
                log.debug(String.format("Read %d bytes into suffix buffer", suffixBufferLength));
            }
        }
    } finally {
        if (fc != null) {
            fc.close();
        }
        if (localFile != null) {
            localFile.close();
        }
    }
    log.info(String.format("Read %d bytes from remote file, added %d to destination buffer",
            totalPrefixRead + totalRequestedRead + totalSuffixRead, totalRequestedRead));
    return totalRequestedRead;
}

From source file:com.qubole.rubix.core.TestCachedReadRequestChain.java

@Test
public void testCachedReadRequestChain() throws IOException {
    String filename = "/tmp/testCachedReadRequestChainFile";
    populateFile(filename);/*from w w  w  . jav a 2 s  . c  o m*/

    File file = new File(filename);

    byte[] buffer = new byte[1000];
    ReadRequest[] readRequests = { new ReadRequest(0, 100, 0, 100, buffer, 0, file.length()),
            new ReadRequest(200, 300, 200, 300, buffer, 100, file.length()),
            new ReadRequest(400, 500, 400, 500, buffer, 200, file.length()),
            new ReadRequest(600, 700, 600, 700, buffer, 300, file.length()),
            new ReadRequest(800, 900, 800, 900, buffer, 400, file.length()),
            new ReadRequest(1000, 1100, 1000, 1100, buffer, 500, file.length()),
            new ReadRequest(1200, 1300, 1200, 1300, buffer, 600, file.length()),
            new ReadRequest(1400, 1500, 1400, 1500, buffer, 700, file.length()),
            new ReadRequest(1600, 1700, 1600, 1700, buffer, 800, file.length()),
            new ReadRequest(1800, 1900, 1800, 1900, buffer, 900, file.length()) };

    RandomAccessFile raf = new RandomAccessFile(file, "r");
    CachedReadRequestChain cachedReadRequestChain = new CachedReadRequestChain(raf);
    for (ReadRequest rr : readRequests) {
        cachedReadRequestChain.addReadRequest(rr);
    }
    cachedReadRequestChain.lock();
    int readSize = cachedReadRequestChain.call();
    raf.close();

    assertTrue("Wrong amount of data read " + readSize, readSize == 1000);
    String output = new String(buffer, Charset.defaultCharset());
    assertTrue("Wrong data read, expected\n" + getExpectedOutput(readSize) + "\nBut got\n" + output,
            getExpectedOutput(readSize).equals(output));

    file.delete();
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.storage.LocalOffsetStorage.java

public LocalOffsetStorage(final String filePath) throws IOException {
    final File file = new File(filePath);
    if (file.exists()) {
        this.loadGroupInfo(file);
    } else {//from   w  w  w.  jav  a  2 s.co  m
        file.createNewFile();
    }
    this.channel = new RandomAccessFile(file, "rw").getChannel();
}

From source file:com.embedler.moon.jtxt2img.mmap.MappedFileBuffer.java

private MappedFileBuffer(final int type, final int size, final int numBanks) {
    super(type, size, numBanks);

    Validate.isTrue(size >= 0, "Integer overflow for size: %d", size);
    Validate.isTrue(numBanks >= 0, "Number of banks must be positive", numBanks);

    int componentSize = DataBuffer.getDataTypeSize(type) / 8;

    try {// w w  w  .j  a v a  2  s .c  o  m
        tempFile = File.createTempFile(String.format("%s-", getClass().getSimpleName().toLowerCase()), ".tmp");
        try (RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
                FileChannel channel = raf.getChannel()) {

            long length = ((long) size) * componentSize * numBanks;
            raf.setLength(length);

            byteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, length);

            switch (type) {
            case DataBuffer.TYPE_BYTE:
                buffer = byteBuffer;
                break;
            case DataBuffer.TYPE_USHORT:
                buffer = byteBuffer.asShortBuffer();
                break;
            case DataBuffer.TYPE_INT:
                buffer = byteBuffer.asIntBuffer();
                break;
            default:
                throw new IllegalArgumentException("Unsupported data type: " + type);
            }
        } finally {
            if (!tempFile.delete()) {
                tempFile.deleteOnExit();
            }
        }
    } catch (Exception e) {
        throw new JTxt2ImgIoRuntimeException(e);
    }
}