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:com.dmbstream.android.util.Util.java

public static void atomicCopy(File from, File to) throws IOException {
    FileInputStream in = null;
    FileOutputStream out = null;//from ww  w .  ja v  a 2 s.  co m
    File tmp = null;
    try {
        tmp = new File(to.getPath() + ".tmp");
        in = new FileInputStream(from);
        out = new FileOutputStream(tmp);
        in.getChannel().transferTo(0, from.length(), out.getChannel());
        out.close();
        if (!tmp.renameTo(to)) {
            throw new IOException("Failed to rename " + tmp + " to " + to);
        }
        Log.i(TAG, "Copied " + from + " to " + to);
    } catch (IOException x) {
        close(out);
        delete(to);
        throw x;
    } finally {
        close(in);
        close(out);
        delete(tmp);
    }
}

From source file:org.mule.util.FileUtils.java

public static boolean renameFileHard(File srcFile, File destFile) {
    boolean isRenamed = false;
    if (srcFile != null && destFile != null) {
        logger.debug("Moving file " + srcFile.getAbsolutePath() + " to " + destFile.getAbsolutePath());
        if (!destFile.exists()) {
            try {
                if (srcFile.isFile()) {
                    logger.debug("Trying to rename file");
                    FileInputStream in = null;
                    FileOutputStream out = null;
                    try {
                        in = new FileInputStream(srcFile);
                        out = new FileOutputStream(destFile);
                        out.getChannel().transferFrom(in.getChannel(), 0, srcFile.length());
                        isRenamed = true;
                    } catch (Exception e) {
                        logger.debug(e);
                    } finally {
                        if (in != null) {
                            try {
                                in.close();
                            } catch (Exception inNotClosed) {
                                logger.debug(inNotClosed);
                            }/*from   w ww. java2  s . co m*/
                        }
                        if (out != null) {
                            try {
                                out.close();
                            } catch (Exception outNotClosed) {
                                logger.debug(outNotClosed);
                            }
                        }
                    }
                    logger.debug("File renamed: " + isRenamed);
                    if (isRenamed) {
                        srcFile.delete();
                    } else {
                        destFile.delete();
                    }
                } else {
                    logger.debug(srcFile.getAbsolutePath() + " is not a valid file.");
                }
            } catch (Exception e) {
                logger.debug("Error renaming file from " + srcFile.getAbsolutePath() + " to "
                        + destFile.getAbsolutePath());
            }
        } else {
            logger.debug("Error renaming file " + srcFile.getAbsolutePath() + ". Destination file "
                    + destFile.getAbsolutePath() + " already exists.");
        }
    }
    return isRenamed;
}

From source file:com.alibaba.shared.django.DjangoClientTests.java

@Test
public void uploadBigFile() throws Exception {
    File file = new File("/opt/cloud/books/originals/Critical.Thinking.pdf");
    FileInputStream fis = new FileInputStream(file);
    long size = fis.getChannel().size();
    String fileid = djangoClient.uploadFile(fis, DjangoClient.MAX_CHUNK_SIZE, size, "Critical.Thinking", "pdf");
    Assert.assertNotNull(fileid);/*from w ww . j  a  v a2 s. c o m*/
}

From source file:com.baidu.rigel.biplatform.tesseract.util.FileUtils.java

/**
 * readFile//from  w  ww  . ja v a 2  s. c om
 * 
 * @param filePath ?
 * @return byte[]
 */
public static byte[] readFile(String filePath) {
    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_BEGIN, "readFile",
            "[filePath:" + filePath + "]"));
    if (StringUtils.isEmpty(filePath)) {
        LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION, "readFile",
                "[filePath:" + filePath + "]"));
        throw new IllegalArgumentException();

    }
    File file = new File(filePath);

    FileInputStream fin = null;
    FileChannel fcin = null;
    ByteBuffer rbuffer = ByteBuffer.allocate(TesseractConstant.FILE_BLOCK_SIZE);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if (file.exists()) {
        try {
            fin = new FileInputStream(file);
            fcin = fin.getChannel();
            while (fcin.read(rbuffer) != -1) {
                bos.write(rbuffer.array());
            }
        } catch (Exception e) {
            LOGGER.error(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION, "readFile",
                    "[filePath:" + filePath + "]"), e);
        } finally {
            try {
                if (fin != null) {
                    fin.close();
                }
                if (fcin != null) {
                    fcin.close();
                }
                bos.close();
            } catch (Exception e) {
                LOGGER.error(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION, "readFile",
                        "[filePath:" + filePath + "]"), e);
            }

        }
    }

    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "readFile",
            "[filePath:" + filePath + "]"));
    return bos.toByteArray();
}

From source file:it.polito.tellmefirst.parsing.TXTparser.java

public String txtToText(File file) throws TMFVisibleException {
    LOG.debug("[txtToText] - BEGIN");
    String result;/*from  ww w  .j  a  va  2  s .co  m*/
    try {
        FileInputStream stream = new FileInputStream(file);
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        stream.close();
        result = Charset.defaultCharset().decode(bb).toString();
    } catch (Exception e) {
        LOG.error("[txtToText] - EXCEPTION: ", e);
        throw new TMFVisibleException(
                "Problem parsing the file: the TXT document you uploaded seems malformed.");
    }
    LOG.debug("[txtToText] - END");
    return result;
}

From source file:SelfClassLoader.java

private byte[] loadClassBytes(String className) throws ClassNotFoundException {
    try {/* w w w .ja  va  2  s .  c  o  m*/
        String classFile = getClassFile(className);
        FileInputStream fis = new FileInputStream(classFile);
        FileChannel fileC = fis.getChannel();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel outC = Channels.newChannel(baos);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int i = fileC.read(buffer);
            if (i == 0 || i == -1) {
                break;
            }
            buffer.flip();
            outC.write(buffer);
            buffer.clear();
        }
        fis.close();
        return baos.toByteArray();
    } catch (IOException fnfe) {
        throw new ClassNotFoundException(className);
    }
}

From source file:org.mule.util.FileUtils.java

/** 
 * Try to move a file by renaming with backup attempt by copying/deleting via NIO.
 * Creates intermidiate directories as required.
 *//*from  w  w w . j  av  a  2 s .  c o m*/
public static boolean moveFileWithCopyFallback(File sourceFile, File destinationFile) {
    // try fast file-system-level move/rename first
    boolean success = sourceFile.renameTo(destinationFile);

    if (!success) {
        // try again using NIO copy
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(sourceFile);
            if (!destinationFile.exists()) {
                FileUtils.createFile(destinationFile.getPath());
            }
            fos = new FileOutputStream(destinationFile);
            FileChannel srcChannel = fis.getChannel();
            FileChannel dstChannel = fos.getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
            success = sourceFile.delete();
        } catch (IOException ioex) {
            // grr!
            success = false;
        } finally {
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(fos);
        }
    }

    return success;
}

From source file:org.opencastproject.util.FileSupport.java

/**
 * Copies the specified <code>sourceLocation</code> to <code>targetLocation</code> and returns a reference to the
 * newly created file or directory.//  www  .  jav a 2s  .co  m
 * <p/>
 * If <code>targetLocation</code> is an existing directory, then the source file or directory will be copied into this
 * directory, otherwise the source file will be copied to the file identified by <code>targetLocation</code>.
 * <p/>
 * If <code>overwrite</code> is set to <code>false</code>, this method throws an {@link IOException} if the target
 * file already exists.
 * <p/>
 * Note that if <code>targetLocation</code> is a directory than the directory itself, not only its content is copied.
 * 
 * @param sourceFile
 *          the source file or directory
 * @param targetFile
 *          the directory to copy the source file or directory to
 * @param overwrite
 *          <code>true</code> to overwrite existing files
 * @return the created copy
 * @throws IOException
 *           if copying of the file or directory failed
 */
public static File copy(File sourceFile, File targetFile, boolean overwrite) throws IOException {

    // This variable is used when the channel copy files, and stores the maximum size of the file parts copied from source to target
    final int chunk = 1024 * 1024 * 512; // 512 MB

    // This variable is used when the cannel copy fails completely, as the size of the memory buffer used to copy the data from one stream to the other.
    final int bufferSize = 1024 * 1024; // 1 MB 

    File dest = determineDestination(targetFile, sourceFile, overwrite);

    // We are copying a directory
    if (sourceFile.isDirectory()) {
        if (!dest.exists()) {
            dest.mkdirs();
        }
        File[] children = sourceFile.listFiles();
        for (File child : children) {
            copy(child, dest, overwrite);
        }
    }
    // We are copying a file
    else {
        // If dest is not an "absolute file", getParentFile may return null, even if there *is* a parent file.
        // That's why "getAbsoluteFile" is used here
        dest.getAbsoluteFile().getParentFile().mkdirs();
        if (dest.exists())
            delete(dest);

        FileChannel sourceChannel = null;
        FileChannel targetChannel = null;
        FileInputStream sourceStream = null;
        FileOutputStream targetStream = null;
        long size = 0;

        try {
            sourceStream = new FileInputStream(sourceFile);
            targetStream = new FileOutputStream(dest);
            try {
                sourceChannel = sourceStream.getChannel();
                targetChannel = targetStream.getChannel();
                size = targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            } catch (IOException ioe) {
                logger.warn("Got IOException using Channels for copying.");
            } finally {
                // This has to be in "finally", because in 64-bit machines the channel copy may fail to copy the whole file without causing a exception
                if ((sourceChannel != null) && (targetChannel != null) && (size < sourceFile.length()))
                    // Failing back to using FileChannels *but* with chunks and not altogether
                    logger.info("Trying to copy the file in chunks using Channels");
                if (size != sourceFile.length()) {
                    while (size < sourceFile.length())
                        size += targetChannel.transferFrom(sourceChannel, size, chunk);
                }
            }
        } catch (IOException ioe) {
            if ((sourceStream != null) && (targetStream != null) && (size < sourceFile.length())) {
                logger.warn(
                        "Got IOException using Channels for copying in chunks. Trying to use stream copy instead...");
                int copied = 0;
                byte[] buffer = new byte[bufferSize];
                while ((copied = sourceStream.read(buffer, 0, buffer.length)) != -1)
                    targetStream.write(buffer, 0, copied);
            } else
                throw ioe;
        } finally {
            if (sourceChannel != null)
                sourceChannel.close();
            if (sourceStream != null)
                sourceStream.close();
            if (targetChannel != null)
                targetChannel.close();
            if (targetStream != null)
                targetStream.close();
        }

        if (sourceFile.length() != dest.length()) {
            logger.warn("Source " + sourceFile + " and target " + dest + " do not have the same length");
            // TOOD: Why would this happen?
            // throw new IOException("Source " + sourceLocation + " and target " +
            // dest + " do not have the same length");
        }
    }
    return dest;
}

From source file:RegexProperties.java

public void load(FileInputStream inStream) throws IOException, PatternSyntaxException {
    FileChannel fc = inStream.getChannel();

    ByteBuffer bb = ByteBuffer.allocate((int) fc.size());
    fc.read(bb);//from ww  w . j a  v  a  2  s .  c  o m
    bb.flip();
    String fileContent = new String(bb.array());

    Pattern pattern = Pattern.compile("^(.*)$", Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(fileContent);

    while (matcher.find()) {
        String line = matcher.group(1);
        if (line != null && !"".equals(line.trim()) && !line.startsWith("#") && !line.startsWith("!")) {
            String keyValue[] = null;
            if (line.indexOf("=") > 0)
                keyValue = line.split("=", 2);
            else
                keyValue = line.split(":", 2);

            if (keyValue != null) {
                super.put(keyValue[0].trim(), keyValue[1]);
            }
        }
    }
    fc = null;
    bb = null;
}

From source file:com.buaa.cfs.io.nativeio.NativeIO.java

/**
 * Unbuffered file copy from src to dst without tainting OS buffer cache
 * <p>/*from  w w w  .  ja  va  2  s.  c om*/
 * In POSIX platform: It uses FileChannel#transferTo() which internally attempts unbuffered IO on OS with native
 * sendfile64() support and falls back to buffered IO otherwise.
 * <p>
 * It minimizes the number of FileChannel#transferTo call by passing the the src file size directly instead of a
 * smaller size as the 3rd parameter. This saves the number of sendfile64() system call when native sendfile64() is
 * supported. In the two fall back cases where sendfile is not supported, FileChannle#transferTo already has its own
 * batching of size 8 MB and 8 KB, respectively.
 * <p>
 * In Windows Platform: It uses its own native wrapper of CopyFileEx with COPY_FILE_NO_BUFFERING flag, which is
 * supported on Windows Server 2008 and above.
 * <p>
 * Ideally, we should use FileChannel#transferTo() across both POSIX and Windows platform. Unfortunately, the
 * wrapper(Java_sun_nio_ch_FileChannelImpl_transferTo0) used by FileChannel#transferTo for unbuffered IO is not
 * implemented on Windows. Based on OpenJDK 6/7/8 source code, Java_sun_nio_ch_FileChannelImpl_transferTo0 on
 * Windows simply returns IOS_UNSUPPORTED.
 * <p>
 * Note: This simple native wrapper does minimal parameter checking before copy and consistency check (e.g., size)
 * after copy. It is recommended to use wrapper function like the Storage#nativeCopyFileUnbuffered() function in
 * hadoop-hdfs with pre/post copy checks.
 *
 * @param src The source path
 * @param dst The destination path
 *
 * @throws IOException
 */
public static void copyFileUnbuffered(File src, File dst) throws IOException {
    if (nativeLoaded && Shell.WINDOWS) {
        copyFileUnbuffered0(src.getAbsolutePath(), dst.getAbsolutePath());
    } else {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel input = null;
        FileChannel output = null;
        try {
            fis = new FileInputStream(src);
            fos = new FileOutputStream(dst);
            input = fis.getChannel();
            output = fos.getChannel();
            long remaining = input.size();
            long position = 0;
            long transferred = 0;
            while (remaining > 0) {
                transferred = input.transferTo(position, remaining, output);
                remaining -= transferred;
                position += transferred;
            }
        } finally {
            IOUtils.cleanup(LOG, output);
            IOUtils.cleanup(LOG, fos);
            IOUtils.cleanup(LOG, input);
            IOUtils.cleanup(LOG, fis);
        }
    }
}