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 final long read(ByteBuffer[] dsts) throws IOException 

Source Link

Document

Reads a sequence of bytes from this channel into the given buffers.

Usage

From source file:org.hawk.service.api.utils.APIUtils.java

public static File convertJavaFileToThriftFile(java.io.File rawFile) throws FileNotFoundException, IOException {
    try (FileInputStream fIS = new FileInputStream(rawFile)) {
        FileChannel chan = fIS.getChannel();

        /* Note: this cast limits us to 2GB files - this shouldn't
         be a problem, but if it were we could use FileChannel#map
         and call Hawk.Client#registerModels one file at a time. */
        ByteBuffer buf = ByteBuffer.allocate((int) chan.size());
        chan.read(buf);
        buf.flip();/*from ww w .j a  va2  s  .c  o  m*/

        File mmFile = new File();
        mmFile.name = rawFile.getName();
        mmFile.contents = buf;
        return mmFile;
    }
}

From source file:ValidateLicenseHeaders.java

/**
 * Add the default jboss lgpl header//w w  w. j  a v  a 2  s .c om
 */
static void addDefaultHeader(File javaFile) throws IOException {
    if (addDefaultHeader) {
        FileInputStream fis = new FileInputStream(javaFile);
        FileChannel fc = fis.getChannel();
        int size = (int) fc.size();
        ByteBuffer contents = ByteBuffer.allocate(size);
        fc.read(contents);
        fis.close();

        ByteBuffer hdr = ByteBuffer.wrap(DEFAULT_HEADER.getBytes());
        FileOutputStream fos = new FileOutputStream(javaFile);
        fos.write(hdr.array());
        fos.write(contents.array());
        fos.close();
    }

    noheaders.add(javaFile);
}

From source file:password.pwm.util.secure.SecureEngine.java

public static String hash(final File file, final PwmHashAlgorithm hashAlgorithm)
        throws IOException, PwmUnrecoverableException {
    FileInputStream fileInputStream = null;
    try {// w  ww. j  a v a2 s .  c o m
        final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgName());
        fileInputStream = new FileInputStream(file);
        final FileChannel fileChannel = fileInputStream.getChannel();
        final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024 * 8);

        while (fileChannel.read(byteBuffer) > 0) {
            byteBuffer.flip();
            messageDigest.update(byteBuffer);
            byteBuffer.clear();
        }

        return JavaHelper.byteArrayToHexString(messageDigest.digest());

    } catch (NoSuchAlgorithmException | IOException e) {
        final String errorMsg = "unexpected error during file hash operation: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, errorMsg);
        throw new PwmUnrecoverableException(errorInformation);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:ja.lingo.engine.util.EngineFiles.java

private static void appendFile(String fileName, FileOutputStream fos, boolean prependWithLength)
        throws IOException {
    FileInputStream fis = new FileInputStream(fileName);
    FileChannel fic = fis.getChannel();
    FileChannel foc = fos.getChannel();

    ByteBuffer buffer = ByteBuffer.allocate(COPY_BUFFER_SIZE);

    // put header: length (1 int = 4 bytes)
    if (prependWithLength) {
        buffer.putInt((int) new File(fileName).length());
    }//w w w .  j a  v a 2 s.  co  m

    // put body
    do {
        buffer.flip();
        foc.write(buffer);
        buffer.clear();
    } while (fic.read(buffer) != -1);
    fic.close();
    // NOTE: do not close 'foc'

    Files.delete(fileName);
}

From source file:ja.centre.util.io.Files.java

public static void copy(String source, String destination) throws IOException {
    FileInputStream fis = null;//from   w w  w  . j  ava  2s  .c  om
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(destination);

        FileChannel fic = null;
        FileChannel foc = null;
        try {
            fic = fis.getChannel();
            foc = fos.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(COPY_BUFFER_SIZE);
            do {
                buffer.flip();
                foc.write(buffer);
                buffer.clear();
            } while (fic.read(buffer) != -1);
        } finally {
            closeQuietly(fic);
            closeQuietly(foc);
        }
    } finally {
        closeQuietly(fis);
        closeQuietly(fos);
    }
}

From source file:com.igormaznitsa.jcp.utils.PreprocessorUtils.java

@Nonnull
public static byte[] readFileAsByteArray(@Nonnull final File file) throws IOException {
    checkFile(file);/*www. ja  va2s. c  o m*/

    int len = (int) file.length();

    final ByteBuffer buffer = ByteBuffer.allocate(len);
    final FileChannel inChannel = new FileInputStream(file).getChannel();

    try {
        while (len > 0) {
            final int read = inChannel.read(buffer);
            if (read < 0) {
                throw new IOException("Can't read whole file [" + getFilePath(file) + '\'');
            }
            len -= read;
        }
    } finally {
        IOUtils.closeQuietly(inChannel);
    }

    return buffer.array();
}

From source file:jext2.Superblock.java

/**
 * Read superblock using a FileChannel. This is intended for testing and code
 * that just needs the superblock not any file system access.
 *//*from   ww  w .  j a  va2 s  .  c o  m*/
public static Superblock fromFileChannel(FileChannel chan) throws IoError {

    Superblock sb = new Superblock(-1);
    ByteBuffer buf = ByteBuffer.allocate(Constants.EXT2_MIN_BLOCK_SIZE);
    try {
        chan.position(1024);
        chan.read(buf);
    } catch (IOException e) {
        throw new IoError();
    }
    sb.read(buf);

    Superblock.instance = sb;
    return sb;
}

From source file:org.cloudata.core.commitlog.pipe.CommitLogFileChannel.java

public static long readLastIndex(FileChannel ch) throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(Long.SIZE / 8);
    long chSize = ch.size();

    if (chSize > 0) {
        ch.position(chSize > (Long.SIZE / 8) ? chSize - (Long.SIZE / 8) : 0);
        ch.read(buf);
        buf.flip();/*  w  ww. jav a  2 s  . c om*/
        return buf.getLong();
    } else {
        return 0;
    }
}

From source file:me.carpela.network.pt.cracker.tools.ttorrent.Torrent.java

private static String hashFiles(List<File> files, int pieceLenght)
        throws InterruptedException, IOException, NoSuchAlgorithmException {
    int threads = getHashingThreadsCount();
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    ByteBuffer buffer = ByteBuffer.allocate(pieceLenght);
    List<Future<String>> results = new LinkedList<Future<String>>();
    StringBuilder hashes = new StringBuilder();

    long length = 0L;
    int pieces = 0;

    long start = System.nanoTime();
    for (File file : files) {

        length += file.length();//from  www  . j  av a  2  s.c  o  m

        FileInputStream fis = new FileInputStream(file);
        FileChannel channel = fis.getChannel();
        int step = 10;

        try {
            while (channel.read(buffer) > 0) {
                if (buffer.remaining() == 0) {
                    buffer.clear();
                    results.add(executor.submit(new CallableChunkHasher(buffer)));
                }

                if (results.size() >= threads) {
                    pieces += accumulateHashes(hashes, results);
                }

                if (channel.position() / (double) channel.size() * 100f > step) {
                    step += 10;
                }
            }
        } finally {
            channel.close();
            fis.close();
        }
    }

    // Hash the last bit, if any
    if (buffer.position() > 0) {
        buffer.limit(buffer.position());
        buffer.position(0);
        results.add(executor.submit(new CallableChunkHasher(buffer)));
    }

    pieces += accumulateHashes(hashes, results);

    // Request orderly executor shutdown and wait for hashing tasks to
    // complete.
    executor.shutdown();
    while (!executor.isTerminated()) {
        Thread.sleep(10);
    }
    long elapsed = System.nanoTime() - start;

    int expectedPieces = (int) (Math.ceil((double) length / pieceLenght));
    return hashes.toString();
}

From source file:Main.java

public static boolean fileCopy(File srcFile, File dstFile) {
    int length = 1048891;
    FileChannel inC = null;
    FileChannel outC = null;/* ww  w.ja  v  a  2  s.com*/
    try {
        FileInputStream in = new FileInputStream(srcFile);
        FileOutputStream out = new FileOutputStream(dstFile);
        inC = in.getChannel();
        outC = out.getChannel();
        ByteBuffer b = null;
        while (inC.position() < inC.size()) {
            if ((inC.size() - inC.position()) < length) {
                length = (int) (inC.size() - inC.position());
            } else {
                length = 1048891;
            }
            b = ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }

        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (inC != null && inC.isOpen()) {
                inC.close();
            }
            if (outC != null && outC.isOpen()) {
                outC.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}