Example usage for java.nio.channels FileChannel transferTo

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

Introduction

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

Prototype

public abstract long transferTo(long position, long count, WritableByteChannel target) throws IOException;

Source Link

Document

Transfers bytes from this channel's file to the given writable byte channel.

Usage

From source file:com.eucalyptus.blockstorage.DASManager.java

public void dupFile(String oldFileName, String newFileName) {
    FileOutputStream fileOutputStream = null;
    FileChannel out = null;//  w  w w . j a  v  a  2s.  c  o  m
    FileInputStream fileInputStream = null;
    FileChannel in = null;
    try {
        fileOutputStream = new FileOutputStream(new File(newFileName));
        out = fileOutputStream.getChannel();
        fileInputStream = new FileInputStream(new File(oldFileName));
        in = fileInputStream.getChannel();
        in.transferTo(0, in.size(), out);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (fileOutputStream != null) {
            try {
                out.close();
                fileOutputStream.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
        if (fileInputStream != null) {
            try {
                in.close();
                fileInputStream.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
    }
}

From source file:imageuploader.ImgWindow.java

private void generatedImages(String code, File[] files)
        throws IOException, IllegalStateException, FTPIllegalReplyException, FTPException, FtpException {

    int ubicacion;
    File directory = new File(code);
    ArrayList<File> imageList = new ArrayList();
    DefaultListModel mod = (DefaultListModel) jL_Info.getModel();
    if (!directory.exists()) {
        boolean result = directory.mkdir();
        if (!result) {
            JOptionPane.showMessageDialog(rootPane, "Directory -- Error");
        } else {/*  ww  w.j  ava  2s  .  com*/
            File dir, img;
            boolean rst;
            FileChannel source = null;
            FileChannel dest = null;
            FtpCredentials.getInstancia().connect();
            for (int i = 0; i < files.length; i++) {

                int val = 1 + i;
                //Create the Angle directory
                dir = new File(directory, "Angle" + val);
                rst = dir.mkdir();

                //Copy Images
                //DefaultListModel mod = (DefaultListModel)jL_Info.getModel();

                for (int j = 0; j < mod.getSize(); j++) {
                    img = new File(dir, code + "~" + mod.getElementAt(j).toString() + ".jpg");
                    rst = img.createNewFile();
                    imageList.add(img);
                    source = new RandomAccessFile(files[i], "rw").getChannel();
                    dest = new RandomAccessFile(img, "rw").getChannel();

                    long position = 0;
                    long count = source.size();
                    source.transferTo(position, count, dest);

                    if (source != null) {
                        source.close();
                    }
                    if (dest != null) {
                        dest.close();
                    }

                }
                ubicacion = i + 1;
                /*Using the private library  */
                if (jCHBox_MY.isSelected()) {
                    FtpCredentials.getInstancia().getClient().setDir("/Myron/angle" + ubicacion + "Flash");
                    FtpCredentials.getInstancia().copyImage(imageList);
                }
                if (jCHB_CA.isSelected()) {
                    FtpCredentials.getInstancia().getClient().setDir("/canada/angle" + ubicacion + "Flash");
                    FtpCredentials.getInstancia().copyImage(imageList);
                }
                if (jCHB_AZ.isSelected()) {
                    FtpCredentials.getInstancia().getClient().setDir("/australia/angle" + ubicacion + "Flash");
                    FtpCredentials.getInstancia().copyImage(imageList);
                }
                imageList.clear();

            }

            mod.removeAllElements();
            jTF_StyleCode.setText("");
            //jL_Info.removeAll();
            //list.removeAllElements();
            JOptionPane.showMessageDialog(rootPane, "Images uploaded");
        }
    } else {
        JOptionPane.showMessageDialog(rootPane, "There is a folder with the same name in the same location");
    }

}

From source file:it.doqui.index.ecmengine.business.personalization.importer.ArchiveImporterJob.java

private boolean copyFile(File in, File out) {
    boolean bRet = false;

    FileChannel inChannel = null;
    FileChannel outChannel = null;

    try {//from www  . ja va  2 s  .c om
        inChannel = new FileInputStream(in).getChannel();
        outChannel = new FileOutputStream(out).getChannel();

        // On the Windows plateform, you can't copy a file bigger than 64Mb, an
        // Exception in thread "main" java.io.IOException: Insufficient system
        // resources exist to complete the requested service is thrown.
        // inChannel.transferTo(0, inChannel.size(), outChannel);

        // magic number for Windows, 64Mb - 32Kb)
        int maxCount = (64 * 1024 * 1024) - (32 * 1024);
        long size = inChannel.size();
        long position = 0;
        while (position < size) {
            position += inChannel.transferTo(position, maxCount, outChannel);
        }

        bRet = true;

    } catch (IOException e) {
        //System.out.println( e );
        //throw e;
    } finally {
        try {
            if (inChannel != null)
                inChannel.close();
        } catch (IOException e) {
        }
        try {
            if (outChannel != null)
                outChannel.close();
        } catch (IOException e) {
        }
    }
    return bRet;
}

From source file:com.dotmarketing.util.ImportExportUtil.java

/**
 *
 * @param zipFile//from  w  w w.  j a v  a 2 s .  co m
 * @return
 */
public boolean validateZipFile(File zipFile) {

    String tempdir = getBackupTempFilePath();
    try {
        deleteTempFiles();

        File ftempDir = new File(tempdir);
        ftempDir.mkdirs();
        File tempZip = new File(tempdir + File.separator + zipFile.getName());
        tempZip.createNewFile();
        FileChannel ic = new FileInputStream(zipFile).getChannel();
        FileChannel oc = new FileOutputStream(tempZip).getChannel();

        // to handle huge zipfiles
        ic.transferTo(0, ic.size(), oc);

        ic.close();
        oc.close();

        /*
         * Unzip zipped backups
         */
        if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) {
            ZipFile z = new ZipFile(zipFile);
            ZipUtil.extract(z, new File(backupTempFilePath));
        }
        return true;

    } catch (Exception e) {
        Logger.error(this, "Error with file", e);
        return false;
    }
}

From source file:edu.cornell.med.icb.goby.modes.ConcatenateCompactReadsMode.java

/**
 * This version does a quick concat. It does NO filtering. It gathers no stats,
 * but, will quickly concat multiple compact-reads files together using NIO.
 * It should be noted that this method is >MUCH< faster.
 * Copy all of the input files except the last MessageChunksWriter.DELIMITER_LENGTH
 * bytes of the first n-1 input files and the entire last input file
 * to the output file./*  w  w  w .j  a v  a  2s . c o  m*/
 * @throws IOException
 */
private void performQuickConcat() throws IOException {
    System.out.println("quick concatenating files");
    File outputFile = new File(outputFilename);
    if (outputFile.exists()) {
        System.err.println("The output file already exists. Please delete it before running concat.");
        return;
    }
    outputFile.createNewFile();

    FileChannel input = null;
    FileChannel output = null;
    long maxChunkSize = 10 * 1024 * 1024; // 10 megabytes at a chunk
    try {
        output = new FileOutputStream(outputFile).getChannel();
        int lastFileNumToCopy = inputFiles.size() - 1;
        int curFileNum = 0;
        for (final File inputFile : inputFiles) {
            System.out.printf("Reading from %s%n", inputFile);
            input = new FileInputStream(inputFile).getChannel();
            long bytesToCopy = input.size();
            if (curFileNum++ < lastFileNumToCopy) {
                // Compact-reads files end with a delimiter (8 x 0xff)
                // followed by a 4 byte int 0 (4 x 0x00). Strip
                // these on all but the last file.
                bytesToCopy -= (MessageChunksWriter.DELIMITER_LENGTH + 1
                        + MessageChunksWriter.SIZE_OF_MESSAGE_LENGTH);
            }

            // Copy the file about 10 megabytes at a time. It would probably
            // be marginally faster to just tell NIO to copy the ENTIRE file
            // in one go, but with very large files Java will freeze until the
            // entire chunck is copied so this makes for a more responsive program
            // should you want to ^C in the middle of the copy. Also, with the single
            // transferTo() you might not see any file size changes in the output file
            // until the entire copy is complete.
            long position = 0;
            while (position < bytesToCopy) {
                long bytesToCopyThisTime = Math.min(maxChunkSize, bytesToCopy - position);
                position += input.transferTo(position, bytesToCopyThisTime, output);
            }
            input.close();
            input = null;
        }
        System.out.printf("Concatenated %d files.%n", lastFileNumToCopy + 1);
    } finally {
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
    }
}

From source file:com.vegnab.vegnab.MainVNActivity.java

public void copyFile(File src, File dst) throws IOException {
    FileInputStream in = new FileInputStream(src);
    FileOutputStream out = new FileOutputStream(dst);
    FileChannel fromChannel = null, toChannel = null;
    try {/* ww  w  . ja  v  a 2 s  .c om*/
        fromChannel = in.getChannel();
        toChannel = out.getChannel();
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        if (fromChannel != null)
            fromChannel.close();
        if (toChannel != null)
            toChannel.close();
    }
    in.close();
    out.close();
    // must do following or file is not visible externally
    MediaScannerConnection.scanFile(getApplicationContext(), new String[] { dst.getAbsolutePath() }, null,
            null);
}

From source file:com.benefit.buy.library.http.query.AbstractAQuery.java

/**
 * Create a temporary file on EXTERNAL storage (sdcard) that holds the cached content of the url. Returns null if
 * url is not cached, or the system cannot create such file (sdcard is absent, such as in emulator). The returned
 * file is accessable to all apps, therefore it is ideal for sharing content (such as photo) via the intent
 * mechanism. <br>/*from www.j a v a  2  s. c  o  m*/
 * <br>
 * Example Usage:
 * 
 * <pre>
 * Intent intent = new Intent(Intent.ACTION_SEND);
 * intent.setType(&quot;image/jpeg&quot;);
 * intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
 * startActivityForResult(Intent.createChooser(intent, &quot;Share via:&quot;), 0);
 * </pre>
 * 
 * <br>
 * The temp file will be deleted when AQUtility.cleanCacheAsync is invoked, or the file can be explicitly deleted
 * after use.
 * @param url The url of the desired cached content.
 * @param filename The desired file name, which might be used by other apps to describe the content, such as an
 *            email attachment.
 * @return temp file
 */
public File makeSharedFile(String url, String filename) {
    File file = null;
    try {
        File cached = getCachedFile(url);
        if (cached != null) {
            File temp = AQUtility.getTempDir();
            if (temp != null) {
                file = new File(temp, filename);
                file.createNewFile();
                FileInputStream fis = new FileInputStream(cached);
                FileOutputStream fos = new FileOutputStream(file);
                FileChannel ic = fis.getChannel();
                FileChannel oc = fos.getChannel();
                try {
                    ic.transferTo(0, ic.size(), oc);
                } finally {
                    AQUtility.close(fis);
                    AQUtility.close(fos);
                    AQUtility.close(ic);
                    AQUtility.close(oc);
                }
            }
        }
    } catch (Exception e) {
        AQUtility.debug(e);
    }
    return file;
}

From source file:semlink.apps.uvig.Generator.java

/**
 * Performs a low-level copy of one file into another.
 *
 * @param src  the source file//www  .j a va  2 s.  c om
 * @param dest the destination file
 * @see        uvi.Generator#copySupplementalFiles()
 */
private static void copyFile(File src, File dest) {
    try {
        FileChannel sourceChannel = new FileInputStream(src).getChannel();
        FileChannel destinationChannel = new FileOutputStream(dest).getChannel();

        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);

        sourceChannel.close();
        destinationChannel.close();
    } catch (Exception e) {
        eprintln("ERROR: Problem copying image file  \"" + src.getName() + "\" to output directory.  "
                + e.getMessage());
    }
}

From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java

/**
 * Copy Files from One location to Other
 * @param Source File//from   ww w. ja  va 2s . com
 * @param target File
 * @param Boolean Value
 * @throws FileNotFoundException
 */
public void copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend) {
    //log("Copying files with channels.");
    //ensureTargetDirectoryExists(aTargetFile.getParentFile());
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    FileInputStream inStream = null;
    FileOutputStream outStream = null;
    try {
        try {
            inStream = new FileInputStream(aSourceFile);
            inChannel = inStream.getChannel();
            outStream = new FileOutputStream(aTargetFile, aAppend);
            outChannel = outStream.getChannel();
            long bytesTransferred = 0;
            //defensive loop - there's usually only a single iteration :
            while (bytesTransferred < inChannel.size()) {
                bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel);
            }
        } finally {
            //being defensive about closing all channels and streams 
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
            if (inStream != null)
                inStream.close();
            if (outStream != null)
                outStream.close();
        }
    } catch (FileNotFoundException ex) {
        System.out.println("File not found: " + ex);
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

From source file:com.tandong.sa.aq.AbstractAQuery.java

/**
 * Create a temporary file on EXTERNAL storage (sdcard) that holds the cached content of the url.
 * Returns null if url is not cached, or the system cannot create such file (sdcard is absent, such as in emulator).
 * //from w  w w  .  ja  v a 2  s  . co  m
 * The returned file is accessable to all apps, therefore it is ideal for sharing content (such as photo) via the intent mechanism.
 * 
 * <br>
 * <br>
 * Example Usage:
 * 
 * <pre>
 *   Intent intent = new Intent(Intent.ACTION_SEND);
 *   intent.setType("image/jpeg");
 *   intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
 *   startActivityForResult(Intent.createChooser(intent, "Share via:"), 0);
 * </pre>
 * 
 * <br>
 * The temp file will be deleted when AQUtility.cleanCacheAsync is invoked, or the file can be explicitly deleted after use.
 * 
 * @param url The url of the desired cached content.
 * @param filename The desired file name, which might be used by other apps to describe the content, such as an email attachment.
 * @return temp file
 * 
 */

public File makeSharedFile(String url, String filename) {

    File file = null;

    try {

        File cached = getCachedFile(url);

        if (cached != null) {

            File temp = AQUtility.getTempDir();

            if (temp != null) {

                file = new File(temp, filename);
                file.createNewFile();

                FileChannel ic = new FileInputStream(cached).getChannel();
                FileChannel oc = new FileOutputStream(file).getChannel();
                try {
                    ic.transferTo(0, ic.size(), oc);
                } finally {
                    if (ic != null)
                        ic.close();
                    if (oc != null)
                        oc.close();
                }

            }
        }

    } catch (Exception e) {
        AQUtility.debug(e);
    }

    return file;
}