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.slytechs.capture.StreamFactory.java

public <T extends InputCapture<? extends FilePacket>> T newInput(final Class<T> t, final File file,
        Filter<ProtocolFilterTarget> filter) throws IOException {

    final BufferedInputStream b = new BufferedInputStream(new FileInputStream(file));
    b.mark(1024); // Buffer first 1K of stream so we can rewind

    /*//from  www .  j a  va2 s  .  co m
     * Check the stream, without decompression first
     */
    if (formatType(Channels.newChannel(b)) != null) {
        b.close();

        /*
         * This is a plain uncompressed file, open up a FileChannel. It will be
         * much faster
         */
        return newInput(t, new RandomAccessFile(file, "rw").getChannel(), filter);
    }

    /*
     * Try with gunziped stream, second
     */
    b.reset(); // Rewind
    if (formatType(Channels.newChannel(new GZIPInputStream(b))) != null) {
        b.close();

        /*
         * Now reopen the same file, but this time without the buffered
         * inputstream in the middle. Try to make things as efficient as possible.
         * TODO: implement much faster channel based GZIP decompression algorithm
         */
        return newInput(t, Channels.newChannel(new GZIPInputStream(new FileInputStream(file))), filter);
    }

    throw new IllegalArgumentException(
            "File is not any compressed or decompressed known format [" + file.getName() + "]");

}

From source file:com.github.neoio.nio.util.NIOUtils.java

public static FileLock tryLock(File file) {
    FileLock toReturn = null;//from   ww  w.  j  a v a  2s.c  o  m

    try {
        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        try {
            FileChannel channel = raf.getChannel();
            toReturn = channel.tryLock();
            raf.writeBytes("lock file for: " + ManagementFactory.getRuntimeMXBean().getName());
        } finally {
            if (toReturn == null)
                raf.close();
        }
    } catch (OverlappingFileLockException e) {
        toReturn = null;
    } catch (FileNotFoundException e) {
        toReturn = null;
    } catch (IOException e) {
        toReturn = null;
    }

    return toReturn;
}

From source file:com.antsdb.saltedfish.nosql.DumpRow.java

private void dump() throws Exception {
    if (this.isVerbose) {
        String str = BytesUtil.toHex(this.key);
        str = StringUtils.replace(str, "\n", "\n     ");
        println("key: %s", str);
    }/*  ww w.java 2  s  . co m*/

    // find tablet files

    this.findTabletFiles(this.home);
    Collections.sort(this.files);
    Collections.reverse(this.files);

    // create mapped buffers

    for (File i : this.files) {
        try (RandomAccessFile raf = new RandomAccessFile(i, "r")) {
            Tablet tablet = new Tablet();
            this.tablets.add(tablet);
            tablet.buf = raf.getChannel().map(MapMode.READ_ONLY, 0, i.length());
            ;
            tablet.file = i;
        }
        if (isVerbose) {
            println("loading file: %s", i);
        }
    }

    // find row

    List<Long> sprows = new ArrayList<>();
    for (Tablet tablet : this.tablets) {
        MappedByteBuffer buf = tablet.buf;
        long addr = UberUtil.getAddress(buf);
        BluntHeap heap = new BluntHeap(addr + MemTablet.HEADER_SIZE, 0);
        heap.position(buf.capacity() - MemTablet.HEADER_SIZE);
        FishSkipList slist = FishSkipList.alloc(heap, new VariableLengthLongComparator());
        long pHead = slist.get(this.pKey);
        if (pHead == 0) {
            continue;
        }
        dumpRowVersions(tablet, heap, pHead, sprows);
    }

    // dump each row

    for (long spRow : sprows) {
        dumpRow(spRow);
    }
}

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 www  . ja  v  a2  s . com*/
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:fr.letroll.ttorrentandroid.client.storage.FileStorage.java

/**
 * Move the partial file to its final location.
 *//*from w  w w  . j a v  a  2  s .c o  m*/
@Override
public synchronized void finish() throws IOException {
    logger.debug("Closing file channel to {} (download complete).", this.current.getName());
    if (this.channel.isOpen())
        this.channel.force(true);

    // Nothing more to do if we're already on the target file.
    if (this.isFinished())
        return;

    this.raf.close();
    FileUtils.deleteQuietly(this.target);
    FileUtils.moveFile(this.current, this.target);
    logger.info("Moved torrent data from {} to {}.", this.current.getName(), this.target.getName());
    this.current = this.target;

    logger.debug("Re-opening torrent byte storage at {}.", this.target.getAbsolutePath());

    this.raf = new RandomAccessFile(this.target, "rw");
    this.raf.setLength(this.size);
    this.channel = this.raf.getChannel();
}

From source file:net.gleamynode.oil.impl.wal.store.FileLogStore.java

public void open() {
    if (isOpen()) {
        throw new IllegalStateException();
    }/*from  w w  w .  ja  v  a  2 s .  co m*/

    parseProperties();

    try {
        File parentDir = file.getCanonicalFile().getParentFile();

        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
    } catch (IOException e) {
        throw new OilException("failed to get parent directory path.", e);
    }

    RandomAccessFile raf = null;

    if (!useExternalCatalog) {
        catalog = new ClassCatalog(file.getPath() + ".cat");
    }

    boolean done = false;

    try {
        raf = new RandomAccessFile(file, "rw");
        raf.seek(0L);
        reader = new FileLogReader(catalog, raf, new FileInputStream(raf.getFD()), maxItemSize);
        raf = new RandomAccessFile(file, "rw");
        raf.seek(raf.length());
        writer = new FileLogWriter(catalog, new FileOutputStream(raf.getFD()), maxItemSize);

        flusher = new Flusher();
        flusher.start();
        done = true;
    } catch (IOException e) {
        throw new OilException(e);
    } finally {
        if (!done) {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }

                reader = null;
            }

            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                }

                writer = null;
            }

            if (!useExternalCatalog) {
                catalog.close();
            }
        }
    }
}

From source file:Hash.Hash.java

private static byte[] getPointers(ArrayList<ifdField> imageLocationFields, File file, boolean endian)
        throws IOException {
    /*      RawImageDigest
            Tag 50972 (C71C.H)//from w  ww.  j  ava  2 s. c  o m
            Type BYTE
            Count 16
            Value See below
            Default Optional
            Usage IFD 0
            Description
            This tag is an MD5 digest of the raw image data. All pixels in the image are processed in rowscan
            order. Each pixel is zero padded to 16 or 32 bits deep (16-bit for data less than or equal to
            16 bits deep, 32-bit otherwise). The data for each pixel is processed in little-endian byte order         */
    long imageLength;
    long imageWidth;
    long pieceOffsets = 0;
    long pieceOffsetsCount = 0;
    int pieceOffsetsLength = 0;
    long pieceLength;
    long pieceWidth = 1;
    long pieceByteCounts = 0;
    long pieceByteCountsCount = 0;
    int pieceByteLength = 0;
    Iterator<ifdField> iterator = imageLocationFields.iterator();
    while (iterator.hasNext()) {
        ifdField field = iterator.next();
        switch (field.tag) {
        case 256:
            imageWidth = field.offset;
            break;
        case 257:
            imageLength = field.offset;
            break;
        case 273:
        case 324:
            pieceOffsets = field.offset;
            pieceOffsetsCount = field.count;
            pieceOffsetsLength = field.getTypeLength();
            break;
        case 322:
            pieceWidth = field.offset;
            break;
        case 278:
        case 323:
            pieceLength = field.offset;
            break;
        case 279:
        case 325:
            pieceByteCounts = field.offset;
            pieceByteCountsCount = field.count;
            pieceByteLength = field.getTypeLength();
            break;
        }
    }
    if (pieceByteCountsCount != pieceOffsetsCount)
        return null;
    try (RandomAccessFile fileRand = new RandomAccessFile(file.getAbsolutePath(), "r")) {
        MessageDigest md5Digest = null;
        try {
            md5Digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            return null;
        }
        if (pieceOffsetsCount == 1) {
            System.out.println(file.getName() + " bytes readed: " + pieceByteCounts + " File size "
                    + file.length() + " % " + (100 * pieceByteCounts / file.length()));
            fileRand.seek(pieceOffsets);
            long readed = 0;
            int bufferSize = 4096;
            while (readed + bufferSize < pieceByteCounts) {
                byte chunk[] = new byte[bufferSize];
                int read = fileRand.read(chunk);
                if (read == -1)
                    return null;
                readed += read;
                md5Digest.update(chunk);
            }
            int residue = (int) (pieceByteCounts - readed);
            byte chunk[] = new byte[residue];
            int read = fileRand.read(chunk);
            if (read == -1)
                return null;
            md5Digest.update(chunk);
        } else {
            long totalread = 0;
            for (int j = 0; j < pieceOffsetsCount; j++) {
                fileRand.seek(pieceByteCounts + j * pieceByteLength);
                long actualPieceBytes = 0;
                for (int i = 0; i < pieceByteLength; i++) {
                    long c = fileRand.read();
                    if (endian) {
                        c = (long) (c * Math.pow(256, i));
                    } else {
                        c = (long) (c * Math.pow(256, pieceByteLength - i));
                    }
                    actualPieceBytes += c;
                }
                //            System.out.println("Count [" + j + "] =" + actualPieceBytes);
                fileRand.seek(pieceOffsets + j * pieceOffsetsLength);
                long actualPieceOffset = 0;
                for (int i = 0; i < pieceOffsetsLength; i++) {
                    long c = fileRand.read();
                    if (endian) {
                        c = (long) (c * Math.pow(256, i));
                    } else {
                        c = (long) (c * Math.pow(256, pieceOffsetsLength - i));
                    }
                    actualPieceOffset += c;
                }
                totalread += actualPieceBytes;
                //            System.out.println("Offset [" + j + "] =" + actualPieceOffset);
                fileRand.seek(actualPieceOffset);
                long readed = 0;
                int bufferSize = 4096;
                while (readed + bufferSize < actualPieceBytes) {
                    byte chunk[] = new byte[bufferSize];
                    int read = fileRand.read(chunk);
                    if (read == -1)
                        return null;
                    readed += read;
                    md5Digest.update(chunk);
                }
                int residue = (int) (actualPieceBytes - readed);
                byte chunk[] = new byte[residue];
                int read = fileRand.read(chunk);
                if (read == -1)
                    return null;
                md5Digest.update(chunk);
            }
            System.out.println(file.getName() + " bytes readed: " + totalread + " File size " + file.length()
                    + " % " + (100 * totalread / file.length()));
        }
        return md5Digest.digest();
    }
}

From source file:com.datatorrent.lib.io.fs.TailFsInputOperator.java

@Override
public void activate(OperatorContext ctx) {
    try {/*from   w  w  w .j  a v a 2 s .  co m*/
        file = new File(filePath);
        reader = new RandomAccessFile(file, "r");
        position = end ? file.length() : position;
        reader.seek(position);
        accessTime = System.currentTimeMillis();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.appspresso.api.fs.DefaultFile.java

/**
 * {@inheritDoc}//from   w  ww .j a  va  2 s  .  com
 * <p>
 * NOTE : ?   ? ?.
 * </p>
 */
@Override
public void open(int mode) throws IOException {
    if (fileStream != null) {
        throw new IOException("The stream already was opened.");
    }

    switch (mode) {
    // case MODE_READ :
    // // TODO
    // break;
    // case MODE_WRITE :
    // // TODO
    // break;
    case MODE_READ_WRITE:
        fileStream = new DefaultFileStream(new RandomAccessFile(peer, "rws"));
        break;
    default:
        throw new IOException("It's an unsupported mode.");
    }
}

From source file:com.netease.qa.emmagee.utils.CpuInfo.java

/**
 * get CPU name.//from w w w .j av a2 s .  c  o  m
 * 
 * @return CPU name
 */
public String getCpuName() {
    try {
        RandomAccessFile cpuStat = new RandomAccessFile(CPU_INFO_PATH, "r");
        // check cpu type
        String line;
        while (null != (line = cpuStat.readLine())) {
            String[] values = line.split(":");
            if (values[0].contains(INTEL_CPU_NAME) || values[0].contains("Processor")) {
                cpuStat.close();
                Log.d(LOG_TAG, "CPU name=" + values[1]);
                return values[1];
            }
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "IOException: " + e.getMessage());
    }
    return "";
}