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:io.github.eternalbits.compactvd.CompactVD.java

private void compact(File file, int options) throws IOException {
    long mtime = file.lastModified();
    task = DiskImageProgress.COMPACT;/*from www  . j av  a 2  s  .c  om*/
    try (RandomAccessFile check = new RandomAccessFile(file, "r")) { // is file?
        try (DiskImage image = DiskImages.open(file, "rw")) {
            FileLock fileLock = image.tryLock();
            verboseProgress(SEARCHING_SPACE);
            image.addObserver(this, false);
            image.optimize(options);
            image.removeObserver(this);
            if (!isCancelled()) {
                verboseProgress("Compacting " + file.getName());
                image.addObserver(this, false);
                image.compact();
                image.removeObserver(this);
            }
            fileLock.release();
        }
    } finally {
        System.out.println(String.format(mtime != file.lastModified() ? IMAGE_CHANGED : IMAGE_NOT_CHANGED,
                file.getName()));
    }
}

From source file:com.wondersgroup.cloud.deployment.file.FileServerHandler.java

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;//from w  w w .  ja v  a2  s  .  co  m
    }

    String srcPath = request.getHeader("srcPath");
    String ipList = request.getHeader("ipList");
    // ??app test: D:\cloud-deploy\DSC01575.JPG
    final String path = srcPath;// sanitizeUri(request.getUri()); "D:\\cloud-deploy\\AppTest.war";// 
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);

    response.setHeader("Content-disposition", "attachment;filename=" + file.getName());

    Channel ch = e.getChannel();

    // Write the initial line and the header.
    ch.write(response);

    // Write the content.
    ChannelFuture writeFuture;
    if (ch.getPipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = ch.write(region);
        writeFuture.addListener(new ChannelFutureProgressListener() {
            public void operationComplete(ChannelFuture future) {
                region.releaseExternalResources();
            }

            public void operationProgressed(ChannelFuture future, long amount, long current, long total) {
                System.out.printf("%s: %d / %d (+%d)%n", path, current, total, amount);
            }
        });
    }

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

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

/**
 * read the status of CPU./*from  w  w w.  j a v a 2 s.  c  om*/
 * 
 * @throws FileNotFoundException
 */
public void readCpuStat() {
    String processPid = Integer.toString(pid);
    String cpuStatPath = "/proc/" + processPid + "/stat";
    try {
        // monitor cpu stat of certain process
        RandomAccessFile processCpuInfo = new RandomAccessFile(cpuStatPath, "r");
        String line = "";
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.setLength(0);
        while ((line = processCpuInfo.readLine()) != null) {
            stringBuffer.append(line + "\n");
        }
        String[] tok = stringBuffer.toString().split(" ");
        processCpu = Long.parseLong(tok[13]) + Long.parseLong(tok[14]);
        processCpuInfo.close();
    } catch (FileNotFoundException e) {
        Log.w(LOG_TAG, "FileNotFoundException: " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    }
    readTotalCpuStat();
}

From source file:WordList.java

public WordList(String filename) throws IOException {
    // Open the random access file for read-only access
    f = new RandomAccessFile(filename, "r");

    // Now read the array of file positions from it
    int numwords = f.readInt(); // Read array length
    positions = new long[numwords]; // Allocate array
    for (int i = 0; i < numwords; i++)
        // Read array contents
        positions[i] = f.readLong();//from  ww w  .j  av a 2s  .  c  o m
}

From source file:com.owncloud.android.lib.common.network.FileRequestEntity.java

@Override
public void writeRequest(final OutputStream out) throws IOException {
    //byte[] tmp = new byte[4096];
    ByteBuffer tmp = ByteBuffer.allocate(4096);
    int readResult = 0;

    //                    globally in some fashionable manner
    RandomAccessFile raf = new RandomAccessFile(mFile, "r");
    FileChannel channel = raf.getChannel();
    Iterator<OnDatatransferProgressListener> it = null;
    long transferred = 0;
    long size = mFile.length();
    if (size == 0)
        size = -1;/*from w  w w.  ja va2s  .  co  m*/
    try {
        while ((readResult = channel.read(tmp)) >= 0) {
            out.write(tmp.array(), 0, readResult);
            tmp.clear();
            transferred += readResult;
            synchronized (mDataTransferListeners) {
                it = mDataTransferListeners.iterator();
                while (it.hasNext()) {
                    it.next().onTransferProgress(readResult, transferred, size, mFile.getAbsolutePath());
                }
            }
        }

    } catch (IOException io) {
        Log_OC.e("FileRequestException", io.getMessage());
        throw new RuntimeException(
                "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really",
                io);

    } finally {
        channel.close();
        raf.close();
    }
}

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

public FixedByteSkipListSCMVWriter(File file, int numDocs, int totalNumValues, int columnSizeInBytes)
        throws Exception {
    float averageValuesPerDoc = totalNumValues / numDocs;
    this.docsPerChunk = (int) (Math.ceil(PREFERRED_NUM_VALUES_PER_CHUNK / averageValuesPerDoc));
    this.numChunks = (numDocs + docsPerChunk - 1) / docsPerChunk;
    chunkOffsetHeaderSize = numChunks * SIZE_OF_INT * NUM_COLS_IN_HEADER;
    bitsetSize = (totalNumValues + 7) / 8;
    rawDataSize = totalNumValues * columnSizeInBytes;
    totalSize = chunkOffsetHeaderSize + bitsetSize + rawDataSize;
    raf = new RandomAccessFile(file, "rw");
    chunkOffsetsBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, chunkOffsetHeaderSize, file,
            this.getClass().getSimpleName() + " chunkOffsetsBuffer");
    bitsetBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, chunkOffsetHeaderSize, bitsetSize,
            file, this.getClass().getSimpleName() + " bitsetBuffer");
    rawDataBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, chunkOffsetHeaderSize + bitsetSize,
            rawDataSize, file, this.getClass().getSimpleName() + " rawDataBuffer");

    chunkOffsetsWriter = new FixedByteWidthRowColDataFileWriter(chunkOffsetsBuffer, numDocs, NUM_COLS_IN_HEADER,
            new int[] { SIZE_OF_INT });

    customBitSet = CustomBitSet.withByteBuffer(bitsetSize, bitsetBuffer);
    rawDataWriter = new FixedByteWidthRowColDataFileWriter(rawDataBuffer, totalNumValues, 1,
            new int[] { columnSizeInBytes });

}

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

private void createBuffer(File file) throws FileNotFoundException, IOException {
    raf = new RandomAccessFile(file, "rw");
    int bytesRequired = SizeUtil.computeBytesRequired(numRows, numBits, uncompressedSize);
    LOGGER.info("Creating byteBuffer of size:{} to store {} values of bits:{}", bytesRequired, numRows,
            numBits);//from   w  ww.j a va  2  s .c  o m
    byteBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, bytesRequired, file,
            this.getClass().getSimpleName() + " byteBuffer");
    isMmap = true;
    ownsByteBuffer = true;
    byteBuffer.position(0);
}

From source file:pydio.sdk.java.http.AjxpFileBody.java

public void writeTo(OutputStream out) {

    InputStream in;/*from   w  ww  .  jav a2  s  . c  o  m*/
    //int bufsize = Integer.parseInt(StateHolder.getInstance().getLocalConfig(Pydio.LOCAL_CONFIG_BUFFER_SIZE));

    try {
        if (this.chunkSize > 0) {
            RandomAccessFile raf = new RandomAccessFile(getFile(), "r");
            int start = chunkIndex * this.chunkSize;

            int count = 0;
            int limit = chunkSize;
            byte[] buffer = new byte[bufsize];

            if (chunkIndex == (totalChunks - 1)) {
                limit = lastChunkSize;
            }

            raf.seek(start);

            while (count < limit) {

                if (count + bufsize > limit) {
                    if (count == 0) {
                        bufsize = limit;
                    } else {
                        bufsize = limit - count;
                    }
                }

                raf.read(buffer, 0, bufsize);
                out.write(buffer, 0, bufsize);
                count += bufsize;
            }
            raf.close();
        } else {
            in = new FileInputStream(getFile());
            byte[] buf = new byte[bufsize];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
        }
        this.chunkIndex++;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

public FixedByteSkipListMultiValueWriter(File file, int numDocs, int totalNumValues, int columnSizeInBytes)
        throws Exception {
    float averageValuesPerDoc = totalNumValues / numDocs;
    this.docsPerChunk = (int) (Math.ceil(PREFERRED_NUM_VALUES_PER_CHUNK / averageValuesPerDoc));
    this.numChunks = (numDocs + docsPerChunk - 1) / docsPerChunk;
    chunkOffsetHeaderSize = numChunks * SIZE_OF_INT * NUM_COLS_IN_HEADER;
    bitsetSize = (totalNumValues + 7) / 8;
    rawDataSize = totalNumValues * columnSizeInBytes;
    totalSize = chunkOffsetHeaderSize + bitsetSize + rawDataSize;
    raf = new RandomAccessFile(file, "rw");
    chunkOffsetsBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, chunkOffsetHeaderSize, file,
            this.getClass().getSimpleName() + " chunkOffsetsBuffer");
    bitsetBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, chunkOffsetHeaderSize, bitsetSize,
            file, this.getClass().getSimpleName() + " bitsetBuffer");
    rawDataBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, chunkOffsetHeaderSize + bitsetSize,
            rawDataSize, file, this.getClass().getSimpleName() + " rawDataBuffer");

    chunkOffsetsWriter = new FixedByteSingleValueMultiColWriter(chunkOffsetsBuffer, numDocs, NUM_COLS_IN_HEADER,
            new int[] { SIZE_OF_INT });

    customBitSet = CustomBitSet.withByteBuffer(bitsetSize, bitsetBuffer);
    rawDataWriter = new FixedByteSingleValueMultiColWriter(rawDataBuffer, totalNumValues, 1,
            new int[] { columnSizeInBytes });

}

From source file:com.cerema.cloud2.lib.common.network.FileRequestEntity.java

@Override
public void writeRequest(final OutputStream out) throws IOException {
    //byte[] tmp = new byte[4096];
    ByteBuffer tmp = ByteBuffer.allocate(4096);
    int readResult = 0;

    // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it
    //                    globally in some fashionable manner
    RandomAccessFile raf = new RandomAccessFile(mFile, "r");
    FileChannel channel = raf.getChannel();
    Iterator<OnDatatransferProgressListener> it = null;
    long transferred = 0;
    long size = mFile.length();
    if (size == 0)
        size = -1;/*  w  ww .ja v  a2  s .c  o m*/
    try {
        while ((readResult = channel.read(tmp)) >= 0) {
            out.write(tmp.array(), 0, readResult);
            tmp.clear();
            transferred += readResult;
            synchronized (mDataTransferListeners) {
                it = mDataTransferListeners.iterator();
                while (it.hasNext()) {
                    it.next().onTransferProgress(readResult, transferred, size, mFile.getAbsolutePath());
                }
            }
        }

    } catch (IOException io) {
        Log_OC.e("FileRequestException", io.getMessage());
        throw new RuntimeException(
                "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really",
                io);

    } finally {
        channel.close();
        raf.close();
    }
}