List of usage examples for java.nio.channels FileChannel transferFrom
public abstract long transferFrom(ReadableByteChannel src, long position, long count) throws IOException;
From source file:com.thinkberg.moxo.vfs.s3.jets3t.Jets3tFileObject.java
protected void doAttach() throws Exception { if (!attached) { try {//from w w w. j a va 2 s. c o m object = service.getObject(bucket, getS3Key()); System.err.println("Attached file to S3 Object: " + object); InputStream is = object.getDataInputStream(); if (object.getContentLength() > 0) { ReadableByteChannel rbc = Channels.newChannel(is); FileChannel cacheFc = getCacheFileChannel(); cacheFc.transferFrom(rbc, 0, object.getContentLength()); cacheFc.close(); rbc.close(); } else { is.close(); } } catch (S3ServiceException e) { object = new S3Object(bucket, getS3Key()); object.setLastModifiedDate(new Date()); System.err.println("Attached file to new S3 Object: " + object); } attached = true; } }
From source file:forge.gui.ImportDialog.java
private static void _copyFile(final File srcFile, final File destFile, final boolean deleteSrcAfter) throws IOException { destFile.getParentFile().mkdirs();// w ww .jav a2s. co m // if this is a move, try a simple rename first if (deleteSrcAfter) { if (srcFile.renameTo(destFile)) { return; } } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFile).getChannel(); dest = new FileOutputStream(destFile).getChannel(); dest.transferFrom(src, 0, src.size()); } finally { if (src != null) { src.close(); } if (dest != null) { dest.close(); } } if (deleteSrcAfter) { srcFile.delete(); } }
From source file:at.ac.tuwien.infosys.util.ImageUtil.java
private void saveFile(URL url, Path file) throws IOException { ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileChannel channel = FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)); channel.transferFrom(rbc, 0, Long.MAX_VALUE); channel.close();/*w w w .j av a 2 s . com*/ }
From source file:hk.hku.cecid.corvus.http.EnvelopQuerySender.java
/** * [@EVENT] This method is invoked when received the reply HTTP response from the server. * <br/><br/>/*from www .j a va2 s. c o m*/ * It saves the response body stream and then available to get through by {@link #getEnvelopStream()} */ protected void onResponse() throws Exception { HttpMethod post = this.getExecutedMethod(); InputStream ins = post.getResponseBodyAsStream(); /* * We have to pipe the content to either memory or storage because the response stream * is directly extracted from socket which is going to close upon the connection * has been closed. */ if (ins.available() < THRESHOLD) { byte[] envelop = IOHandler.readBytes(ins); this.envelopStream = new ByteArrayInputStream(envelop); } else { // Create a temporary file at TMP directory. File envelopTmp = new File(BASE_PATH + this.hashCode()); envelopTmp.deleteOnExit(); // Pipe the content to the TMP file. FileChannel fChannel = new FileInputStream(envelopTmp).getChannel(); fChannel.transferFrom(Channels.newChannel(ins), 0, ins.available()); fChannel.close(); // Create an buffered stream to the file. this.envelopStream = new BufferedInputStream(new FileInputStream(envelopTmp)); // InputStream is closed automatically. } }
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.//from w w w .j ava 2 s .c o 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:com.thinkberg.vfs.s3.jets3t.Jets3tFileObject.java
protected InputStream doGetInputStream() throws Exception { if (!contentCached) { object = service.getObject(bucket, getS3Key()); LOG.debug(String.format("caching content of '%s'", object.getKey())); InputStream objectInputStream = object.getDataInputStream(); if (object.getContentLength() > 0) { ReadableByteChannel rbc = Channels.newChannel(objectInputStream); FileChannel cacheFc = getCacheFile().getChannel(); cacheFc.transferFrom(rbc, 0, object.getContentLength()); cacheFc.close();//from w ww. j av a 2s.c o m rbc.close(); } else { objectInputStream.close(); } contentCached = true; } return Channels.newInputStream(getCacheFile().getChannel()); }
From source file:org.geoserver.rest.util.IOUtils.java
/** * Optimize version of copy method for file channels. * /*from w w w .j a va 2 s .co m*/ * @param bufferSize size of the temp buffer to use for this copy. * @param source the source {@link ReadableByteChannel}. * @param destination the destination {@link WritableByteChannel};. * @throws IOException in case something bad happens. */ public static void copyFileChannel(int bufferSize, FileChannel source, FileChannel destination) throws IOException { inputNotNull(source, destination); if (!source.isOpen() || !destination.isOpen()) throw new IllegalStateException("Source and destination channels must be open."); FileLock lock = null; try { lock = destination.lock(); final long sourceSize = source.size(); long pos = 0; while (pos < sourceSize) { // read and flip final long remaining = (sourceSize - pos); final int mappedZoneSize = remaining >= bufferSize ? bufferSize : (int) remaining; destination.transferFrom(source, pos, mappedZoneSize); // update zone pos += mappedZoneSize; } } finally { if (lock != null) { try { lock.release(); } catch (Throwable t) { if (LOGGER.isLoggable(Level.INFO)) LOGGER.log(Level.INFO, t.getLocalizedMessage(), t); } } } }
From source file:com.homesnap.webserver.AbstractRestApi.java
protected void copyFileUsingFileChannels(File source, File dest) throws IOException { FileChannel inputChannel = null; FileChannel outputChannel = null; try {// ww w . ja v a2s . c om inputChannel = new FileInputStream(source).getChannel(); outputChannel = new FileOutputStream(dest).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } finally { inputChannel.close(); outputChannel.close(); } }
From source file:com.sds.acube.ndisc.mts.xserver.util.XNDiscUtils.java
/** * ? //from w w w .ja v a 2s.co m * * @param nFile * NFile * @param bForwardMedia * ? ? * @param bForce * * @throws Exception */ public static void copyNFile(NFile[] nFile, boolean bForwardMedia, boolean bForce) throws Exception { FileChannel srcChannel = null; FileChannel dstChannel = null; String srcFile = null; String dstFile = null; try { for (int i = 0; i < nFile.length; i++) { if (false == bForce && XNDiscConfig.STAT_NONE.equals(nFile[i].getStatType())) { continue; } else { if (bForwardMedia) { srcFile = nFile[i].getTmpPath(); dstFile = nFile[i].getStoragePath(); } else { srcFile = nFile[i].getStoragePath(); dstFile = nFile[i].getTmpPath(); } srcChannel = new FileInputStream(srcFile).getChannel(); dstChannel = new FileOutputStream(dstFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (bForwardMedia) { new File(srcFile).delete(); } } } } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (null != srcChannel && srcChannel.isOpen()) { srcChannel.close(); } if (null != dstChannel && dstChannel.isOpen()) { dstChannel.close(); } } }
From source file:org.apache.nifi.file.FileUtils.java
/** * Copies the given source file to the given destination file. The given * destination will be overwritten if it already exists. * * @param source/*from w ww . ja va2 s. c o m*/ * @param destination * @param lockInputFile if true will lock input file during copy; if false * will not * @param lockOutputFile if true will lock output file during copy; if false * will not * @param move if true will perform what is effectively a move operation * rather than a pure copy. This allows for potentially highly efficient * movement of the file but if not possible this will revert to a copy then * delete behavior. If false, then the file is copied and the source file is * retained. If a true rename/move occurs then no lock is held during that * time. * @param logger if failures occur, they will be logged to this logger if * possible. If this logger is null, an IOException will instead be thrown, * indicating the problem. * @return long number of bytes copied * @throws FileNotFoundException if the source file could not be found * @throws IOException * @throws SecurityException if a security manager denies the needed file * operations */ public static long copyFile(final File source, final File destination, final boolean lockInputFile, final boolean lockOutputFile, final boolean move, final Logger logger) throws FileNotFoundException, IOException { FileInputStream fis = null; FileOutputStream fos = null; FileLock inLock = null; FileLock outLock = null; long fileSize = 0L; if (!source.canRead()) { throw new IOException("Must at least have read permission"); } if (move && source.renameTo(destination)) { fileSize = destination.length(); } else { try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); final FileChannel in = fis.getChannel(); final FileChannel out = fos.getChannel(); if (lockInputFile) { inLock = in.tryLock(0, Long.MAX_VALUE, true); if (null == inLock) { throw new IOException("Unable to obtain shared file lock for: " + source.getAbsolutePath()); } } if (lockOutputFile) { outLock = out.tryLock(0, Long.MAX_VALUE, false); if (null == outLock) { throw new IOException( "Unable to obtain exclusive file lock for: " + destination.getAbsolutePath()); } } long bytesWritten = 0; do { bytesWritten += out.transferFrom(in, bytesWritten, TRANSFER_CHUNK_SIZE_BYTES); fileSize = in.size(); } while (bytesWritten < fileSize); out.force(false); FileUtils.closeQuietly(fos); FileUtils.closeQuietly(fis); fos = null; fis = null; if (move && !FileUtils.deleteFile(source, null, 5)) { if (logger == null) { FileUtils.deleteFile(destination, null, 5); throw new IOException("Could not remove file " + source.getAbsolutePath()); } else { logger.warn( "Configured to delete source file when renaming/move not successful. However, unable to delete file at: " + source.getAbsolutePath()); } } } finally { FileUtils.releaseQuietly(inLock); FileUtils.releaseQuietly(outLock); FileUtils.closeQuietly(fos); FileUtils.closeQuietly(fis); } } return fileSize; }