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:edu.harvard.iq.dataverse.dataaccess.StorageIOTest.java

@Test
public void testGetChannel() throws FileNotFoundException {
    assertEquals(null, instance.getChannel());
    Channel c = new RandomAccessFile("src/main/java/Bundle.properties", "r").getChannel();
    instance.setChannel(c);//from  w w w . j a v a  2  s  .  c  om
    assertEquals(c, instance.getChannel());
}

From source file:org.datagator.api.client.SpooledRowBuffer.java

public SpooledRowBuffer(int cacheLimit) throws IOException {
    this.cache = new ArrayList<Object[]>();
    File tempFile = File.createTempFile("dg_Cache_", ".tmp");
    tempFile.deleteOnExit();/*from   ww  w.  j a va2s  .  c o  m*/
    this.cacheFile = new RandomAccessFile(tempFile, "rw");
    this.cacheLimit = cacheLimit;
}

From source file:com.louding.frame.http.download.FileEntityHandler.java

public File handleEntity(HttpEntity entity, DownloadProgress callback, File save, boolean isResume)
        throws IOException {
    long current = 0;
    RandomAccessFile file = new RandomAccessFile(save, "rw");
    if (isResume) {
        current = file.length();/*from  w  ww  . j  a  v a2s. co m*/
    }
    InputStream input = entity.getContent();
    long count = entity.getContentLength() + current;
    if (mStop) {
        FileUtils.closeIO(file);
        return save;
    }
    // ???????
    /**
     *  <br>
     * current = input.skip(current); <br>
     * file.seek(current); <br>
     * ?JDKInputstream.skip(long i)i<br>
     * ? n ???????
     */
    file.seek(input.skip(current));

    int readLen = 0;
    byte[] buffer = new byte[1024];

    while ((readLen = input.read(buffer, 0, 1024)) != -1) {
        if (mStop) {
            break;
        } else {
            file.write(buffer, 0, readLen);
            current += readLen;
            callback.onProgress(count, current);
        }
    }
    callback.onProgress(count, current);

    if (mStop && current < count) { // ?
        FileUtils.closeIO(file);
        throw new IOException("user stop download thread");
    }
    FileUtils.closeIO(file);
    return save;
}

From source file:com.splunk.shuttl.archiver.util.UtilsFile.java

/**
 * @param file/*from w w w  .ja v a 2 s  .c o  m*/
 * @return
 */
public static RandomAccessFile getRandomAccessFileSilent(File file) {
    try {
        return new RandomAccessFile(file, "rw");
    } catch (FileNotFoundException e) {
        logger.debug(did("Created a RandomAccessFile for file: " + file.getAbsolutePath(), e,
                "To create the RandomAccessFile object", "file", file, "exception", e));
        throw new RuntimeException(e);
    }
}

From source file:com.adaptris.fs.NioWorkerTest.java

@Test
public void testLockWhileWriting() throws Exception {
    NioWorker worker = createWorker();/*from   www . j  av  a2 s .  c o m*/
    File f = File.createTempFile(this.getClass().getSimpleName(), "");
    f.delete();
    try {
        RandomAccessFile raf = new RandomAccessFile(f, "rwd");
        FileLock lock = raf.getChannel().lock();
        try {
            // Use the write method, because this "bypasses" the file.exists() check
            worker.write(BYTES, f);
            fail();
        } catch (FsException expected) {
            assertEquals(OverlappingFileLockException.class, expected.getCause().getClass());
        }
        lock.release();
        raf.close();
        f.delete();
        worker.put(BYTES, f);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:com.ejisto.services.startup.ConstraintsVerifier.java

@Override
public void execute() {
    log.info("checking if there is another process already running");
    File lockFile = new File(System.getProperty("ejisto.home"), ".lock");
    try {/*from  w  w  w .j  a  va 2 s.  co m*/
        if (!lockFile.exists() && !lockFile.createNewFile()) {
            throw new IllegalStateException("Unable to create lock file.");
        }
        FileLock lock = new RandomAccessFile(lockFile, "rw").getChannel().tryLock();
        if (lock == null) {
            throw new IllegalStateException("There is another instance already running. Ejisto won't start.");
        }

    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    log.info("checking System properties");
    String agentPath = ContainerUtils.extractAgentJar(System.getProperty("java.class.path"));
    if (!StringUtils.isNotBlank(agentPath)) {
        log.warn("**************************************************");
        log.warn("**       ejisto-agent not found in path.        **");
        log.warn("**          Check your configuration!           **");
        log.warn("**************************************************");
    } else {
        System.setProperty("ejisto.agent.jar.path", agentPath);
    }
}

From source file:com.cloudhopper.commons.io.demo.FileServerMain.java

public static void loadFilesFromDir(String dir, int threads) {
    ThreadPoolExecutor ex = new ThreadPoolExecutor(threads, threads, 5000l, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    ex.prestartAllCoreThreads();/*from  w  w w .  ja v a  2 s  .  c o  m*/

    IdGenerator idGen = new UUIDIdGenerator();
    final FileStore store = new SimpleNIOFileStore(idGen, "/tmp/fileStore/");

    final long start = System.currentTimeMillis();
    int count = 0;

    Iterator<File> it = FileUtils.iterateFiles(new File(dir), null, true);
    while (it.hasNext()) {
        final File f = it.next();
        final int num = count++;
        Runnable job = new Runnable() {

            @Override
            public void run() {
                try {
                    RandomAccessFile randomAccessFile = new RandomAccessFile(f, "r");
                    FileChannel fileChannel = randomAccessFile.getChannel();
                    Id id = store.write(fileChannel);
                    System.out.println("(" + num + ") Stored " + f.getPath() + " as " + id.getName() + " after "
                            + (System.currentTimeMillis() - start) + "ms");
                } catch (Exception e) {
                    logger.error("", e);
                }
            }
        };
        ex.execute(job);
    }
}

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

public FixedByteSingleValueMultiColWriter(File file, int rows, int cols, int[] columnSizes) throws Exception {
    this.file = file;
    this.rows = rows;
    this.cols = cols;
    this.columnOffsets = new int[cols];
    raf = new RandomAccessFile(file, "rw");
    rowSizeInBytes = 0;//from   www.  j  a  v a 2  s.  co m
    for (int i = 0; i < columnSizes.length; i++) {
        columnOffsets[i] = rowSizeInBytes;
        int colSize = columnSizes[i];
        rowSizeInBytes += colSize;
    }
    int totalSize = rowSizeInBytes * rows;
    byteBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, totalSize, file,
            this.getClass().getSimpleName() + " byteBuffer");
    ownsByteBuffer = true;
}

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

public FixedByteWidthRowColDataFileWriter(File file, int rows, int cols, int[] columnSizes) throws Exception {
    this.file = file;
    this.rows = rows;
    this.cols = cols;
    this.columnOffsets = new int[cols];
    raf = new RandomAccessFile(file, "rw");
    rowSizeInBytes = 0;/*w w w . j av a 2 s  .  c  o m*/
    for (int i = 0; i < columnSizes.length; i++) {
        columnOffsets[i] = rowSizeInBytes;
        int colSize = columnSizes[i];
        rowSizeInBytes += colSize;
    }
    int totalSize = rowSizeInBytes * rows;
    byteBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, totalSize, file,
            this.getClass().getSimpleName() + " byteBuffer");
    ownsByteBuffer = true;
}

From source file:com.thoughtworks.go.config.GoConfigFileWriter.java

public synchronized void writeToConfigXmlFile(String content) {
    FileChannel channel = null;//from   www. jav a2  s. c  o m
    FileOutputStream outputStream = null;
    FileLock lock = null;

    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
        channel = randomAccessFile.getChannel();
        lock = channel.lock();
        randomAccessFile.seek(0);
        randomAccessFile.setLength(0);
        outputStream = new FileOutputStream(randomAccessFile.getFD());

        IOUtils.write(content, outputStream, UTF_8);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (channel != null && lock != null) {
            try {
                lock.release();
                channel.close();
                IOUtils.closeQuietly(outputStream);
            } catch (IOException e) {
                LOGGER.error("Error occured when releasing file lock and closing file.", e);
            }
        }
    }
}