Example usage for java.io FileInputStream getChannel

List of usage examples for java.io FileInputStream getChannel

Introduction

In this page you can find the example usage for java.io FileInputStream getChannel.

Prototype

public FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file input stream.

Usage

From source file:Main.java

@SuppressWarnings("unused")
private static boolean copy2SingleFileByChannel(File sourceFile, File destFile) {
    boolean copyOK = true;
    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {/*from   www .  j a v a2  s .c  o m*/
        inputStream = new FileInputStream(sourceFile);
        outputStream = new FileOutputStream(destFile);
        inputChannel = inputStream.getChannel();
        outputChannel = outputStream.getChannel();
        inputChannel.transferTo(0, inputChannel.size(), outputChannel);
    } catch (Exception e) {
        copyOK = false;
    } finally {
        try {
            inputChannel.close();
            inputStream.close();
            outputChannel.close();
            outputStream.close();
        } catch (IOException e) {
            copyOK = false;
            e.printStackTrace();
        }
    }
    return copyOK;
}

From source file:org.socialbiz.cog.BackupUtils.java

private static void copyFile(File srcFile, File destFile) throws IOException {
    FileInputStream is = null;
    FileOutputStream os = null;// w w w .  j av  a  2 s  . c om
    try {

        is = new FileInputStream(srcFile);
        FileChannel iChannel = is.getChannel();

        os = new FileOutputStream(destFile, false);
        FileChannel oChannel = os.getChannel();

        long doneBytes = 0L;
        long todoBytes = srcFile.length();

        while (todoBytes != 0L) {

            //Return the smallest of two
            long iterationBytes = Math.min(todoBytes, DEFAULT_COPY_BUFFER_SIZE);

            long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes);

            if (iterationBytes != transferredLength) {
                throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only "
                        + transferredLength + " bytes copied.");
            }
            doneBytes += transferredLength;
            todoBytes -= transferredLength;
        }
    } finally {
        if (is != null) {
            is.close();
        }
        if (os != null) {
            os.close();
        }
    }
    boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified());
    if (!successTimestampOp) {
        log.info("Could not change timestamp for {}. Index synchronization may be slow. " + destFile);
    }
}

From source file:org.polymap.p4.imports.utils.FileGroupHelper.java

private static CoordinateReferenceSystem parseCRS(File prjFile) {
    PrjFileReader prjFileReader = null;/*from  ww  w  .j  av a 2 s.  c  o m*/
    FileInputStream in = null;
    try {
        in = new FileInputStream(prjFile);
        FileChannel channel = in.getChannel();
        prjFileReader = new PrjFileReader(channel);
        return prjFileReader.getCoordinateReferenceSystem();
    } catch (IOException | FactoryException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (prjFileReader != null) {
            try {
                prjFileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.mitre.ccv.mapred.GenerateFeatureVectors.java

/**
 * Returns a read only {@link MappedByteBuffer}.
 * /* w w  w .  j  a  v a 2s.  c o  m*/
 * @param input full <b>local</b>  path 
 * @throws java.io.IOException
 */
public static MappedByteBuffer getMappedByteBuffer(String input) throws IOException {
    FileInputStream fins = new FileInputStream(input);
    FileChannel channel = fins.getChannel();
    return channel.map(FileChannel.MapMode.READ_ONLY, 0, (int) channel.size());
}

From source file:com.cats.version.utils.Utils.java

public static void copyFile(File srcFile, File destFile) {
    FileInputStream fis = null;
    FileOutputStream fos = null;/*www .j ava2  s  .c  om*/
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        FileChannel inChannel = fis.getChannel();
        FileChannel outChannel = fos.getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        Utils.closeRes(fis);
        Utils.closeRes(fos);
    }
}

From source file:com.sunchenbin.store.feilong.core.io.IOReaderUtil.java

/**
 * ?./*from  w w w  .  j  a  v a 2  s .c om*/
 *
 * @param file
 *            
 * @param charsetName
 *            ?,isNullOrEmpty, {@link CharsetType#UTF8}
 * @return the file content
 * @see org.apache.commons.io.FileUtils#readFileToString(File, Charset)
 */
public static String getFileContent(File file, String charsetName) {
    if (Validator.isNullOrEmpty(file)) {
        throw new NullPointerException("the file is null or empty!");
    }
    // ?
    final int capacity = 186140;
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(capacity);
    StringBuilder sb = new StringBuilder(capacity);

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(file);

        // ?????.
        FileChannel fileChannel = fileInputStream.getChannel();
        String useCharsetName = Validator.isNullOrEmpty(charsetName) ? DEFAULT_CHARSET_NAME : charsetName;
        Charset charset = Charset.forName(useCharsetName);
        while (fileChannel.read(byteBuffer) != -1) {
            // ??
            byteBuffer.flip();
            CharBuffer charBuffer = charset.decode(byteBuffer);
            sb.append(charBuffer.toString());
            byteBuffer.clear();
        }
        return sb.toString();

    } catch (FileNotFoundException e) {
        throw new UncheckedIOException(e);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        // ? ,^_^
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:r2b.apps.utils.FileUtils.java

/**
 * Copy src to dst.//from  w  ww.j a  va2 s . c o m
 * @param src Source file.
 * @param dst Destination file.
 */
public static void copy(final File src, File dst) {
    try {
        FileInputStream inStream = new FileInputStream(src);
        FileOutputStream outStream = new FileOutputStream(dst);
        FileChannel inChannel = inStream.getChannel();
        FileChannel outChannel = outStream.getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
        inStream.close();
        outStream.close();
    } catch (IOException e) {
        Logger.e(FileUtils.class.getSimpleName(), e.toString());
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.MappableBlock.java

/**
 * Load the block.//w  w  w. java  2 s . c o m
 *
 * mmap and mlock the block, and then verify its checksum.
 *
 * @param length         The current length of the block.
 * @param blockIn        The block input stream.  Should be positioned at the
 *                       start.  The caller must close this.
 * @param metaIn         The meta file input stream.  Should be positioned at
 *                       the start.  The caller must close this.
 * @param blockFileName  The block file name, for logging purposes.
 *
 * @return               The Mappable block.
 */
public static MappableBlock load(long length, FileInputStream blockIn, FileInputStream metaIn,
        String blockFileName) throws IOException {
    MappableBlock mappableBlock = null;
    MappedByteBuffer mmap = null;
    FileChannel blockChannel = null;
    try {
        blockChannel = blockIn.getChannel();
        if (blockChannel == null) {
            throw new IOException("Block InputStream has no FileChannel.");
        }
        mmap = blockChannel.map(MapMode.READ_ONLY, 0, length);
        NativeIO.POSIX.getCacheManipulator().mlock(blockFileName, mmap, length);
        verifyChecksum(length, metaIn, blockChannel, blockFileName);
        mappableBlock = new MappableBlock(mmap, length);
    } finally {
        IOUtils.closeQuietly(blockChannel);
        if (mappableBlock == null) {
            if (mmap != null) {
                NativeIO.POSIX.munmap(mmap); // unmapping also unlocks
            }
        }
    }
    return mappableBlock;
}

From source file:yui.classes.utils.IOUtils.java

public static byte[] fileReadNIO(String name) {
    FileInputStream f = null;
    ByteBuffer bb = null;/* w  w w.ja v  a  2s. c o  m*/
    try {
        f = new FileInputStream(name);

        FileChannel ch = f.getChannel();
        bb = ByteBuffer.allocateDirect(1024);

        long checkSum = 0L;
        int nRead;
        while ((nRead = ch.read(bb)) != -1) {
            bb.position(0);
            bb.limit(nRead);
            while (bb.hasRemaining()) {
                checkSum += bb.get();
            }
            bb.clear();
        }
    } catch (FileNotFoundException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } finally {
        try {
            f.close();
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
    return bb.array();

}

From source file:gridool.util.xfer.TransferUtils.java

public static void sendfile(@Nonnull final File file, final long fromPos, final long count,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler)
        throws IOException {
    if (!file.exists()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist");
    }//w ww.  j a  v a 2 s. c  o m
    if (!file.isFile()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " is not file");
    }
    if (!file.canRead()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read");
    }

    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    FileInputStream src = null;
    final long nbytes;
    try {
        src = new FileInputStream(file);
        FileChannel fc = src.getChannel();

        String fileName = file.getName();
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long xferBytes = (count == -1L) ? fc.size() : count;
        dos.writeLong(xferBytes);
        dos.writeBoolean(append); // append=false
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        nbytes = fc.transferTo(fromPos, xferBytes, channel);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to "
                    + dstSockAddr.toString() + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != xferBytes) {
                throw new IllegalStateException(
                        "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }

    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}