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.btoddb.fastpersitentqueue.MemorySegmentSerializer.java

public void loadFromDisk(File theFile, MemorySegment segment) throws IOException {
    RandomAccessFile raFile = new RandomAccessFile(theFile, "r");
    try {//from  ww  w .j  a  v a 2  s  .c  o  m
        segment.readFromPagingFile(raFile);
    } finally {
        raFile.close();
    }
}

From source file:com.datasayer.meerkat.MeerJobRunner.java

@SuppressWarnings("unchecked")
@Override/*w  w  w.  jav a  2 s . c  o m*/
public void bsp(final BSPPeer<Writable, Writable, Writable, Writable, Writable> peer)
        throws IOException, SyncException, InterruptedException {

    while (true) {
        try {
            long currentTime = System.currentTimeMillis();
            FileSystem fs = FileSystem.get(conf);
            if (!fs.isFile(logPath)) {
                System.out.println("can not read input file");
                return;
            }
            RandomAccessFile file = new RandomAccessFile(logPath.toString(), "r");
            long fileLength = file.length();

            if (fileLength > filePointer) {
                file.seek(filePointer);
                String line = null;
                while (file.length() > file.getFilePointer()) {
                    line = file.readLine();
                    line = new String(line.getBytes("8859_1"), "utf-8");
                    guardMeer.observe(line);
                }
                filePointer = file.getFilePointer();
            } else {
                // nothing to do
            }
            file.close();

            long timeDiff = currentTime - this.lastAggregatedTime;
            if (timeDiff >= this.aggregationInterval) {

                peer.sync();

                if (peer.getPeerName().equals(masterName)) {
                    bossMeer.masterCompute(new Iterator<Writable>() {

                        private final int producedMessages = peer.getNumCurrentMessages();
                        private int consumedMessages = 0;

                        @Override
                        public boolean hasNext() {
                            return producedMessages > consumedMessages;
                        }

                        @Override
                        public Writable next() throws NoSuchElementException {
                            if (consumedMessages >= producedMessages) {
                                throw new NoSuchElementException();
                            }

                            try {
                                consumedMessages++;
                                return peer.getCurrentMessage();
                            } catch (IOException e) {
                                throw new NoSuchElementException();
                            }
                        }

                        @Override
                        public void remove() {
                            // BSPPeer.getCurrentMessage originally deletes a message.
                            // Thus, it doesn't need to throw exception.
                            // throw new UnsupportedOperationException();
                        }

                    }, signalMeer);
                    this.lastAggregatedTime = currentTime;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:it.geosolutions.tools.io.file.Copy.java

/**
 * Copy the input file onto the output file using the specified buffer size.
 * //from w  ww.  ja va2 s  .  c o  m
 * @param sourceFile
 *            the {@link File} to copy from.
 * @param destinationFile
 *            the {@link File} to copy to.
 * @param size
 *            buffer size.
 * @throws IOException
 *             in case something bad happens.
 */
public static void copyFile(File sourceFile, File destinationFile, int size) throws IOException {
    Objects.notNull(sourceFile, destinationFile);
    if (!sourceFile.exists() || !sourceFile.canRead() || !sourceFile.isFile())
        throw new IllegalStateException("Source is not in a legal state.");
    if (!destinationFile.exists()) {
        destinationFile.createNewFile();
    }
    if (destinationFile.getAbsolutePath().equalsIgnoreCase(sourceFile.getAbsolutePath()))
        throw new IllegalArgumentException("Cannot copy a file on itself");

    RandomAccessFile s = null, d = null;
    FileChannel source = null;
    FileChannel destination = null;
    try {
        s = new RandomAccessFile(sourceFile, "r");
        source = s.getChannel();
        d = new RandomAccessFile(destinationFile, "rw");
        destination = d.getChannel();
        IOUtils.copyFileChannel(size, source, destination);
    } finally {
        if (source != null) {
            try {
                source.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }
        if (s != null) {
            try {
                s.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }

        if (destination != null) {
            try {
                destination.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }

        if (d != null) {
            try {
                d.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }
    }
}

From source file:org.jenkinsci.plugins.relution_publisher.net.requests.ZeroCopyFileRequestProducer.java

public ZeroCopyFileRequestProducer(final ZeroCopyFileRequest request) throws FileNotFoundException {

    this.mRequest = request;

    this.mFile = request.getFile();
    this.mAccessfile = new RandomAccessFile(this.mFile, "r");
}

From source file:com.wet.wired.jsr.player.ScreenPlayer.java

private void openStream() {
    startTime = 0;//from w  w w  . ja v  a 2 s .c o m
    frameTime = 0;
    lastFrameTime = 0;

    frameNr = 0;

    running = false;
    fastForward = false;

    try {

        iStream = new RandomAccessFile(videoFile + ".owl.cap", "r");

        readFrameIndex();

        width = iStream.read();
        width = width << 8;
        width += iStream.read();

        height = iStream.read();
        height = height << 8;
        height += iStream.read();

        area = new Rectangle(width, height);
        decompressor = new FrameDecompressor(iStream, width * height);
    } catch (FileNotFoundException e) {
        log.error("video file not found", e);
        exceptionWindow.show(e, "video file not found");
    } catch (IOException e) {
        log.error("cannot read stream from video", e);
        exceptionWindow.show(e, "cannot read stream from video");
    }

}

From source file:shootersubdownloader.Shootersubdownloader.java

static String computefilehash(File f) throws Exception {
    if (!f.exists() || f.length() < 8 * 1024) {
        return null;
    }/*from  ww w .ja va2 s . c  om*/
    long l = f.length();
    long[] offset = new long[4];
    offset[3] = l - 8 * 1024;
    offset[2] = l / 3;
    offset[1] = l / 3 * 2;
    offset[0] = 4 * 1024;
    byte[] bBuf = new byte[1024 * 4];
    RandomAccessFile raf = new RandomAccessFile(f, "r");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 4; i++) {
        raf.seek(offset[i]);
        int readlen = raf.read(bBuf, 0, 4 * 1024);
        String md5 = md5(bBuf);
        if (sb.length() != 0) {
            sb.append("%3B");
        }
        sb.append(md5);
    }
    raf.close();
    return sb.toString();
}

From source file:fr.gael.dhus.server.ftp.DHuSFtpProduct.java

@Override
public InputStream createInputStream(long offset) throws IOException {
    File file = new File(product.getDownloadablePath());
    logger.debug("Retrieving File stream from " + file.getPath());
    /*/* ww  w  .ja  v  a  2s  . c  o m*/
    return new FileInputStream(file);
    */
    // permission check
    if (!doesExist()) {
        throw new IOException("No read permission : " + file.getName());
    }

    // move to the appropriate offset and create input stream
    final RandomAccessFile raf = new RandomAccessFile(file, "r");
    try {
        raf.seek(offset);
        // The IBM jre needs to have both the stream and the random access file
        // objects closed to actually close the file
        return new RegulatedInputStream.Builder(new FileInputStream(raf.getFD()) {
            public void close() throws IOException {
                super.close();
                raf.close();
            }
        }, TrafficDirection.OUTBOUND).userName(user.getName())
                .copyStreamListener(new DownloadActionRecordListener(product.getUuid(), product.getIdentifier(),
                        vfsService.getDhusUserFromFtpUser(user)))
                .build();
    } catch (IOException e) {
        raf.close();
        throw e;
    }
}

From source file:mi.RankInfo.java

static public int loadFile(String fileName, FloatByteRcd[] o) throws Exception {
    File file = new File(fileName);

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

    final int batchSize = 1000;
    int count = 0;

    FloatByteRcd fbr = null;//from   www .jav a 2s  .  c  o  m
    do {
        fbr = FloatByteRcd.readNext(reader, count);
        if (fbr == null)
            break;

        if (count % batchSize == 0) {
            System.out.println("Loaded " + count + " vectors...");
        }

        o[count++] = fbr;
    } while (true);
    return count;
}

From source file:de.micromata.genome.logging.spi.ifiles.IndexDirectory.java

public IndexDirectory(File ixdFile) throws IOException {
    this.ixdFile = ixdFile;
    boolean createNew = false;
    int mappedSize = DIRIDX_FILE_SIZE_INC;
    if (ixdFile.exists() == false) {
        createNew = true;//from w w  w  . j a v a  2  s. co  m
    }
    idxRandomAccessFile = new RandomAccessFile(ixdFile, "rw");
    indexChannel = idxRandomAccessFile.getChannel();
    int filesize = (int) indexChannel.size();
    indexByteBuffer = indexChannel.map(FileChannel.MapMode.READ_WRITE, 0,
            DIRIDX_FILE_SIZE_INC > filesize ? DIRIDX_FILE_SIZE_INC : filesize);
    if (createNew == true) {
        writeNew();
    } else {
        loadVerify();
    }
}

From source file:com.btoddb.fastpersitentqueue.JournalFileTest.java

@Test
public void testInitForReadingThenClose() throws IOException {
    UUID id = new UUID();
    RandomAccessFile raFile = new RandomAccessFile(theFile, "rw");
    raFile.writeInt(1);//from  w  w  w . j  a  v  a2 s. com
    Utils.writeUuidToFile(raFile, id);
    raFile.writeLong(123);
    raFile.close();

    JournalFile jf1 = new JournalFile(theFile);
    jf1.initForReading();
    assertThat(jf1.getVersion(), is(JournalFile.VERSION));
    assertThat(jf1.getId(), is(id));
    assertThat(jf1.getNumberOfEntries(), is(123L));

    assertThat(jf1.isOpen(), is(true));
    assertThat(jf1.isWriteMode(), is(false));
    assertThat(jf1.getFilePosition(), is((long) JournalFile.HEADER_SIZE));
    jf1.close();

    assertThat(jf1.isOpen(), is(false));
}