Example usage for java.io FileOutputStream getChannel

List of usage examples for java.io FileOutputStream getChannel

Introduction

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

Prototype

public FileChannel getChannel() 

Source Link

Document

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

Usage

From source file:org.apache.pulsar.functions.worker.Utils.java

public static void downloadFromHttpUrl(String destPkgUrl, FileOutputStream outputStream) throws IOException {
    URL website = new URL(destPkgUrl);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    outputStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}

From source file:VASSAL.tools.io.IOUtils.java

/**
 * Copies bytes from a large (over 2GB) <code>FileInputStream</code> to a
 * <code>FileOutputStream</code>.
 *
 * This method uses channels. The input file should not be written
 * to during the copy.//  w w  w.  j a v  a2s .  c  om
 *
 * @param in the source
 * @param out the destination
 * @throws IOException if one occurs while reading or writing
 */
public static long copyLarge(FileInputStream in, FileOutputStream out) throws IOException {
    final FileChannel inc = in.getChannel();
    return inc.transferTo(0L, inc.size(), out.getChannel());
}

From source file:FileHelper.java

private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException {
    FileInputStream is = null;/* w  w  w .  j  a  v a  2 s  .co  m*/
    FileOutputStream os = null;
    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) {
            long iterationBytes = Math.min(todoBytes, chunkSize);
            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) {
        System.out.println("Could not change timestamp for {}. Index synchronization may be slow. " + destFile);
    }
}

From source file:com.hortonworks.amstore.view.AmbariStoreHelper.java

public static void downloadFile(String url, String localFilePath) {

    try {/*  w w w . java2 s  . c om*/
        URL website = new URL(url);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        // unix specific
        FileOutputStream fos = new FileOutputStream(localFilePath);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
    } catch (java.net.MalformedURLException e) {
    } catch (java.io.FileNotFoundException e) {
    } catch (java.io.IOException e) {
    }
}

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

/**
 * Copy src to dst./*  w w w. ja  v a2 s .  com*/
 * @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:prototypes.ws.proxy.soap.commons.io.Files.java

public static String download(String httpPath) {
    String localPath = "";
    LOGGER.debug("Remote file to download : {}", httpPath);
    try {/* w  ww  .j av a 2  s .co  m*/
        File folder = createTempDirectory();
        if (!folder.exists()) {
            folder.mkdir();
        }
        URL url = new URL(httpPath);
        String distantFile = url.getFile();
        if (distantFile != null) {
            int pos = distantFile.lastIndexOf('/');
            if (pos != -1) {
                distantFile = distantFile.substring(pos + 1, distantFile.length());
            }
        }
        localPath = folder.getAbsolutePath() + File.separator + distantFile;
        LOGGER.debug("Local path to save to : {}", localPath);
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        FileOutputStream fos = new FileOutputStream(localPath);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        LOGGER.info("Remote file downloaded.");
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    return localPath;
}

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

public static void copyFile(File srcFile, File destFile) {
    FileInputStream fis = null;//from  w  w w .  j av a 2s  .c o  m
    FileOutputStream fos = null;
    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:org.opf_labs.fmts.droid.ForegCmd.java

public static void downloadAllPronomFormatRecords(File outputFolder) throws Exception {
    SigFile sigFile = SigFileUtils.getLatestSigFile();
    BigInteger version = sigFile.getFFSignatureFile().getVersion();
    System.out.println("Got version " + version);
    String filename = "droid-signature-file.xml";
    try {/*  w w w.  j  a v  a 2  s .  c  om*/
        SigFileUtils.writeSigFileTypeToOutputStream(sigFile.getFFSignatureFile(),
                new FileOutputStream(new File(outputFolder, filename)));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw (e);
    }
    //
    try {
        for (FileFormatType fft : sigFile.getFFSignatureFile().getFileFormatCollection().getFileFormat()) {
            String puid = fft.getPUID();
            String puidFilename = puid + ".xml";
            FileOutputStream fos = new FileOutputStream(new File(outputFolder, puidFilename));
            URL repurl = SigFileUtils.getPronomUrlForPUID(puid);
            System.out.println("Downloading " + repurl + " to " + outputFolder + "/" + puidFilename);
            IOUtils.copy(repurl.openStream(), fos);
            fos.flush();
            fos.getChannel().force(true);
            fos.close();
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw (e);
    }

}

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

private static void copyFile(File srcFile, File destFile) throws IOException {
    FileInputStream is = null;//from   w  w w .j  a va 2s. c om
    FileOutputStream os = null;
    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:cn.com.sunjiesh.wechat.handler.WechatBaseHandler.java

/**
 * ?/*w w  w  .j  av  a  2  s.c  om*/
 *
 * @param httpResponse httpResponse
 * @param fileTpye fileTpye
 * @return File
 * @throws ServiceException ServiceException
 */
public static File getFileResponseFromHttpResponse(HttpResponse httpResponse, String fileTpye)
        throws ServiceException {
    File file = null;

    try {
        StatusLine httpStatusLine = httpResponse.getStatusLine();
        HttpEntity httpEntity = httpResponse.getEntity();
        int statusCode = httpStatusLine.getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error(DOWNLOAD_FILE_ERROR);
            throw new ServiceException(DOWNLOAD_FILE_ERROR);
        }

        String fileName = UUID.randomUUID().toString();
        fileName = fileName + "." + fileTpye;
        InputStream is = httpEntity.getContent();
        if (!StringUtils.isEmpty(fileName)) {
            //??
            file = new File("/var/tmp", fileName);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream fos = new FileOutputStream(file, false);
            FileChannel fileChannel = fos.getChannel();
            ByteBuffer byteBuffer = null;
            byte[] tempBytes = new byte[4096];
            while (is.read(tempBytes) > 0) {
                byteBuffer = ByteBuffer.wrap(tempBytes);
                fileChannel.write(byteBuffer);
            }
            if (fos != null) {
                fos.close();
            }
            fileChannel.close();
        }
    } catch (IllegalStateException e) {
        LOGGER.error(DOWNLOAD_FILE_ERROR, e);
        throw new ServiceException(DOWNLOAD_FILE_ERROR, e);
    } catch (FileNotFoundException e) {
        LOGGER.error(DOWNLOAD_FILE_ERROR, e);
        throw new ServiceException(DOWNLOAD_FILE_ERROR, e);
    } catch (IOException e) {
        LOGGER.error(DOWNLOAD_FILE_ERROR, e);
        throw new ServiceException(DOWNLOAD_FILE_ERROR, e);
    }

    return file;
}