Example usage for java.nio.channels FileChannel read

List of usage examples for java.nio.channels FileChannel read

Introduction

In this page you can find the example usage for java.nio.channels FileChannel read.

Prototype

public abstract int read(ByteBuffer dst, long position) throws IOException;

Source Link

Document

Reads a sequence of bytes from this channel into the given buffer, starting at the given file position.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    FileInputStream fIn = new FileInputStream("test.txt");
    FileChannel fChan = fIn.getChannel();

    long fSize = fChan.size();
    ByteBuffer mBuf = ByteBuffer.allocate((int) fSize);

    fChan.read(mBuf, 10);
    mBuf.rewind();/*w  ww  . ja  va2 s .c om*/

    for (int i = 0; i < fSize; i++) {
        System.out.print((char) mBuf.get());
    }
    fChan.close();
    fIn.close();
}

From source file:BufferConverter.java

public static void main(String[] arguments) {
    try {/* w  w w. j  a v  a  2s  .co m*/
        String data = "friends.dat";
        FileInputStream inData = new FileInputStream(data);
        FileChannel inChannel = inData.getChannel();
        long inSize = inChannel.size();
        ByteBuffer source = ByteBuffer.allocate((int) inSize);
        inChannel.read(source, 0);
        source.position(0);
        for (int i = 0; source.remaining() > 0; i++)
            System.out.print(source.get() + " ");

        source.position(0);
        Charset ascii = Charset.forName("US-ASCII");
        CharsetDecoder toAscii = ascii.newDecoder();
        CharBuffer destination = toAscii.decode(source);
        destination.position(0);
        System.out.println("\n\nNew character data:");
        for (int i = 0; destination.remaining() > 0; i++)
            System.out.print(destination.get());
    } catch (Exception ioe) {
        System.out.println(ioe.getMessage());
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    createFile();//from ww  w .jav  a  2  s. com

    File aFile = new File("C:/primes.bin");
    FileInputStream inFile = new FileInputStream(aFile);

    FileChannel inChannel = inFile.getChannel();

    final int PRIMESREQUIRED = 10;
    ByteBuffer buf = ByteBuffer.allocate(8 * PRIMESREQUIRED);

    long[] primes = new long[PRIMESREQUIRED];
    int index = 0; // Position for a prime in the file

    // Count of primes in the file
    final int PRIMECOUNT = (int) inChannel.size() / 8;

    // Read the number of random primes required
    for (int i = 0; i < PRIMESREQUIRED; i++) {
        index = 8 * (int) (PRIMECOUNT * Math.random());
        inChannel.read(buf, index); // Read the value
        buf.flip();
        primes[i] = buf.getLong(); // Save it in the array
        buf.clear();
    }

    for (long prime : primes) {
        System.out.printf("%12d", prime);
    }
    inFile.close(); // Close the file and the channel

}

From source file:org.apache.hadoop.hdfs.server.datanode.BlockMetadataHeader.java

/**
 * Read the header without changing the position of the FileChannel.
 *
 * @param fc The FileChannel to read./*w  ww.j a v a 2 s . co m*/
 * @return the Metadata Header.
 * @throws IOException on error.
 */
public static BlockMetadataHeader preadHeader(FileChannel fc) throws IOException {
    final byte arr[] = new byte[getHeaderSize()];
    ByteBuffer buf = ByteBuffer.wrap(arr);

    while (buf.hasRemaining()) {
        if (fc.read(buf, 0) <= 0) {
            throw new EOFException("unexpected EOF while reading " + "metadata file header");
        }
    }
    short version = (short) ((arr[0] << 8) | (arr[1] & 0xff));
    DataChecksum dataChecksum = DataChecksum.newDataChecksum(arr, 2);
    return new BlockMetadataHeader(version, dataChecksum);
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java

public static boolean isMMMultipageTiff(String directory) throws IOException {
    File dir = new File(directory);
    File[] children = dir.listFiles();
    File testFile = null;//from   w ww .  jav  a 2s .  com
    for (File child : children) {
        if (child.isDirectory()) {
            File[] grandchildren = child.listFiles();
            for (File grandchild : grandchildren) {
                if (grandchild.getName().endsWith(".tif")) {
                    testFile = grandchild;
                    break;
                }
            }
        } else if (child.getName().endsWith(".tif") || child.getName().endsWith(".TIF")) {
            testFile = child;
            break;
        }
    }
    if (testFile == null) {
        throw new IOException("Unexpected file structure: is this an MM dataset?");
    }
    RandomAccessFile ra;
    try {
        ra = new RandomAccessFile(testFile, "r");
    } catch (FileNotFoundException ex) {
        ReportingUtils.logError(ex);
        return false;
    }
    FileChannel channel = ra.getChannel();
    ByteBuffer tiffHeader = ByteBuffer.allocate(36);
    ByteOrder bo;
    channel.read(tiffHeader, 0);
    char zeroOne = tiffHeader.getChar(0);
    if (zeroOne == 0x4949) {
        bo = ByteOrder.LITTLE_ENDIAN;
    } else if (zeroOne == 0x4d4d) {
        bo = ByteOrder.BIG_ENDIAN;
    } else {
        throw new IOException("Error reading Tiff header");
    }
    tiffHeader.order(bo);
    int summaryMDHeader = tiffHeader.getInt(32);
    channel.close();
    ra.close();
    if (summaryMDHeader == MultipageTiffWriter.SUMMARY_MD_HEADER) {
        return true;
    }
    return false;
}

From source file:xbird.storage.io.RemoteVarSegments.java

public static void handleResponse(final TrackReadRequestMessage request, final ProtocolEncoderOutput out,
        final ConcurrentMap<String, FileChannel> fdCacheMap,
        final ConcurrentMap<String, IDescriptor> directoryCache) throws IOException {
    final String filePath = request.filePath;
    final long[] idxs = request.idxs;
    final int size = idxs.length;

    // look-up directory
    final File dataFile = new File(filePath);
    final long[] offsets = new long[size];
    IDescriptor directory = directoryCache.get(filePath);
    try {/*from   w  w  w  . ja  v  a 2  s.c  om*/
        if (directory == null) {
            directory = VarSegments.initDescriptor(dataFile);
            directoryCache.put(filePath, directory);
        }
        for (int i = 0; i < size; i++) {
            offsets[i] = directory.getRecordAddr(idxs[i]);
        }
    } catch (IOException e) {
        LOG.error(e);
        throw e;
    }

    FileChannel fileChannel = fdCacheMap.get(filePath);
    if (fileChannel == null) {
        if (!dataFile.exists()) {
            throw new IllegalStateException("file not exists: " + filePath);
        }
        final RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(dataFile, "r");
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(e);
        }
        fileChannel = raf.getChannel();
        fdCacheMap.put(filePath, fileChannel);
    }

    for (int i = 0; i < size; i++) {
        final long offset = offsets[i];
        // get data length
        final ByteBuffer tmpBuf = ByteBuffer.allocate(4);
        try {
            fileChannel.read(tmpBuf, offset);
        } catch (IOException e) {
            LOG.error(e);
            throw e;
        }
        tmpBuf.flip();
        final int length = tmpBuf.getInt();
        tmpBuf.rewind();
        IoBuffer ioBuf = IoBuffer.wrap(tmpBuf);
        out.write(ioBuf);
        // attempt zero-copy sendfile
        long position = offset + 4;
        long count = length;
        FileRegion fileRegion = new DefaultFileRegion(fileChannel, position, count);
        out.write(fileRegion);
    }
}

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

private byte[] readChannel(long offset2len, FileChannel channel) throws IOException {
    long offset = getOffset(offset2len);
    int len = getLen(offset2len);
    ByteBuffer data = ByteBuffer.allocate(len);
    channel.read(data, offset);
    return data.array();
}

From source file:voldemort.store.cachestore.voldeimpl.StoreIterator.java

protected byte[] readChannel(long offset2len, FileChannel channel) throws IOException {
    long offset = getOffset(offset2len);
    int len = getLen(offset2len);
    ByteBuffer data = ByteBuffer.allocate(len);
    channel.read(data, offset);
    return data.array();
}

From source file:org.jajuk.util.UtilSystem.java

/**
 * Additional file checksum used to prevent bug #886098. Simply return some
 * bytes read at the middle of the file// ww w  .ja  v a2 s . c  o  m
 * <p>
 * uses nio api for performances
 * 
 * @param fio 
 * 
 * @return the file checksum
 * 
 * @throws JajukException the jajuk exception
 */
public static String getFileChecksum(final File fio) throws JajukException {
    try {
        String sOut = "";
        final FileChannel fc = new FileInputStream(fio).getChannel();
        try {
            final ByteBuffer bb = ByteBuffer.allocate(500);
            fc.read(bb, fio.length() / 2);
            sOut = new String(bb.array());
        } finally {
            fc.close();
        }
        return MD5Processor.hash(sOut);
    } catch (final IOException e) {
        throw new JajukException(103, e);
    }
}

From source file:voldemort.store.cachestore.impl.LogChannel.java

public byte[] readChannel(long offset2len, FileChannel channel) throws IOException {
    long offset = getOffset(offset2len);
    int len = getLen(offset2len);
    ByteBuffer data = ByteBuffer.allocate(len);
    channel.read(data, offset);
    return data.array();
}