当前位置: 首页>>代码示例>>Java>>正文


Java FileChannel.transferTo方法代码示例

本文整理汇总了Java中java.nio.channels.FileChannel.transferTo方法的典型用法代码示例。如果您正苦于以下问题:Java FileChannel.transferTo方法的具体用法?Java FileChannel.transferTo怎么用?Java FileChannel.transferTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.channels.FileChannel的用法示例。


在下文中一共展示了FileChannel.transferTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: copyThrowsOnException

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Copy src file to dst file. FileChannels are used to maximize performance.
 *
 * @param source source File
 * @param destination destination File which will be created or truncated, before copying, if it already exists
 *
 * @throws IOException if any error occurS
 */
public static void copyThrowsOnException(final File source, final File destination) throws IOException {
    // Must be done in a loop as there's no guarantee that a request smaller than request count will complete in one invocation.
    // Setting the transfer size more than about 1MB is pretty pointless because there is no asymptotic benefit. What you're trying
    // to achieve with larger transfer sizes is fewer context switches, and every time you double the transfer size you halve the
    // context switch cost. Pretty soon it vanishes into the noise.
    try (FileInputStream inStream = new FileInputStream(source); FileOutputStream outStream = new FileOutputStream(destination))
    {
        final FileChannel inChannel = inStream.getChannel();
        final FileChannel outChannel = outStream.getChannel();
        final long size = inChannel.size();
        long position = 0;
        while (position < size)
        {
            position += inChannel.transferTo(position, 1024L * 1024L, outChannel);
        }
    } //Closeables closed exiting try block in all circumstances
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:26,代码来源:Utils.java

示例2: moveFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Moves a file to another location
 * @param src source
 * @param dst destination
 * @throws IOException
 */
public static void moveFile(File src, File dst) throws IOException {
    if (!dst.exists()) {
        Log.i("New File", "" + dst.createNewFile());
    }

    FileInputStream inStream = new FileInputStream(src);
    FileOutputStream outStream = new FileOutputStream(dst);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    if (!src.delete()){
        Log.e("moveFile", "Failed to delete file");
    }

    inStream.close();
    outStream.close();
}
 
开发者ID:feup-infolab,项目名称:labtablet,代码行数:24,代码来源:FileMgr.java

示例3: copiarArquivo

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public void copiarArquivo(File source, File destination) throws IOException {
    if (destination.exists()) {
        destination.delete();
    }
    FileChannel sourceChannel = null;
    FileChannel destinationChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destinationChannel = new FileOutputStream(destination).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(),
                destinationChannel);
    } finally {
        if (sourceChannel != null && sourceChannel.isOpen()) {
            sourceChannel.close();
        }
        if (destinationChannel != null && destinationChannel.isOpen()) {
            destinationChannel.close();
        }
    }
}
 
开发者ID:wesleyreis1808,项目名称:projetomcdonalds,代码行数:21,代码来源:ControlerInicial.java

示例4: copyFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
static public void copyFile(String source, String target) throws IOException {
    File sf = new File(source);
    if (!sf.exists()) {
        throw new IllegalArgumentException("source file does not exist.");
    }
    File tf = new File(target);
    tf.getParentFile().mkdirs();
    if (!tf.exists() && !tf.createNewFile()) {
        throw new RuntimeException("failed to create target file.");
    }

    FileChannel sc = null;
    FileChannel tc = null;
    try {
        tc = new FileOutputStream(tf).getChannel();
        sc = new FileInputStream(sf).getChannel();
        sc.transferTo(0, sc.size(), tc);
    } finally {
        if (null != sc) {
            sc.close();
        }
        if (null != tc) {
            tc.close();
        }
    }
}
 
开发者ID:lyy4j,项目名称:rmq4note,代码行数:27,代码来源:IOTinyUtils.java

示例5: copy

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * 复制文件
 * 
 * @param source
 * @param target
 * @throws IOException
 */
public void copy(File source, File target) throws IOException
{
	// FileInputStream sourceStream = null;
	// FileInputStream targetStream = null;
	
	FileChannel inChannel = new FileInputStream(source).getChannel();
	FileChannel outChannel = new FileOutputStream(target).getChannel();
	try
	{
		inChannel.transferTo(0, inChannel.size(), outChannel);
	}
	catch (IOException e)
	{
		Log.E(TAG, "Failed to copy file. " + e.toString());
		e.printStackTrace();
	}
	finally
	{
		if (inChannel != null)
		{
			inChannel.close();
		}
		if (outChannel != null)
		{
			outChannel.close();
		}
		
		// if (targetStream != null)
		// {
		// targetStream.close();
		// }
		// if (sourceStream != null)
		// {
		// sourceStream.close();
		// }
	}
}
 
开发者ID:benniaobuguai,项目名称:android-project-gallery,代码行数:45,代码来源:RestoreManager.java

示例6: transferFrom

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public long transferFrom(final FileChannel src, final long position, final long count) throws IOException {
    if (anyAreSet(state, FLAG_WRITES_SHUTDOWN)) {
        throw new ClosedChannelException();
    }
    return src.transferTo(position, count, new ConduitWritableByteChannel(this));
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:8,代码来源:ChunkedStreamSinkConduit.java

示例7: copyFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static boolean copyFile(File sourceFile, File targetFile) {
    if (!sourceFile.exists()) {
        ProfilerLogger.severe(MessageFormat.format(COPY_FILE_NOT_FOUND_MESSAGE, new Object[] { sourceFile.getAbsolutePath() })); //NOI18N

        return false;
    }

    if (targetFile.exists()) {
        if (!targetFile.delete()) {
            ProfilerLogger.severe(MessageFormat.format(COPY_CANNOT_DELETE_FILE_MESSAGE,
                                                       new Object[] { targetFile.getAbsolutePath() })); //NOI18N

            return false;
        }
    }

    try {
        FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
        try {
            FileChannel destinationChannel = new FileOutputStream(targetFile).getChannel();
            try {
                sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
                return true;
            } finally {
                destinationChannel.close();
            }
        } finally {
            sourceChannel.close();                
        }
    } catch (Exception ex) {
        ProfilerLogger.log(ex);
        ProfilerLogger.severe(MessageFormat.format(COPY_ERROR_MESSAGE,
                                                   new Object[] { sourceFile.getAbsolutePath(), targetFile.getAbsolutePath() })); //NOI18N

        return false;
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:38,代码来源:IntegrationUtils.java

示例8: xferTest07

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Test
public void xferTest07() throws Exception { // for bug 5103988
    File source = File.createTempFile("source", null);
    source.deleteOnExit();

    FileChannel sourceChannel = new RandomAccessFile(source, "rw")
        .getChannel();
    sourceChannel.position(32000L)
        .write(ByteBuffer.wrap("The End".getBytes()));

    // The sink is a non-blocking socket channel
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(new InetSocketAddress(0));
    InetSocketAddress sa = new InetSocketAddress(
        InetAddress.getLocalHost(), ssc.socket().getLocalPort());
    SocketChannel sink = SocketChannel.open(sa);
    sink.configureBlocking(false);
    SocketChannel other = ssc.accept();

    long size = sourceChannel.size();

    // keep sending until congested
    long n;
    do {
        n = sourceChannel.transferTo(0, size, sink);
    } while (n > 0);

    sourceChannel.close();
    sink.close();
    other.close();
    ssc.close();
    source.delete();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:34,代码来源:Transfer.java

示例9: copyFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static void copyFile(File src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null) {
            inChannel.close();
        }
        if (outChannel != null) {
            outChannel.close();
        }
    }
}
 
开发者ID:victordiaz,项目名称:phonk,代码行数:15,代码来源:FileIO.java

示例10: transferFrom

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public long transferFrom(final FileChannel src, final long position, final long count) throws IOException {
    if (anyAreSet(state, FLAG_CLOSE_COMPLETE)) {
        throw new ClosedChannelException();
    }
    return src.transferTo(position, count, new ConduitWritableByteChannel(this));
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:8,代码来源:HeadStreamSinkConduit.java

示例11: expandIfNecessary

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private void expandIfNecessary(int dataLength) throws IOException {
    int elementLength = dataLength + 4;
    int remainingBytes = remainingBytes();
    if (remainingBytes < elementLength) {
        int newLength;
        int previousLength = this.fileLength;
        do {
            remainingBytes += previousLength;
            newLength = previousLength << 1;
            previousLength = newLength;
        } while (remainingBytes < elementLength);
        setLength(newLength);
        int endOfLastElement = wrapPosition((this.last.position + 4) + this.last.length);
        if (endOfLastElement < this.first.position) {
            FileChannel channel = this.raf.getChannel();
            channel.position((long) this.fileLength);
            int count = endOfLastElement - 4;
            if (channel.transferTo(16, (long) count, channel) != ((long) count)) {
                throw new AssertionError("Copied insufficient number of bytes!");
            }
        }
        if (this.last.position < this.first.position) {
            int newLastPosition = (this.fileLength + this.last.position) - 16;
            writeHeader(newLength, this.elementCount, this.first.position, newLastPosition);
            this.last = new Element(newLastPosition, this.last.length);
        } else {
            writeHeader(newLength, this.elementCount, this.first.position, this.last.position);
        }
        this.fileLength = newLength;
    }
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:32,代码来源:QueueFile.java

示例12: copyBookFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private void copyBookFile() throws IOException{
    FileInputStream in = new FileInputStream(bookFile);
    FileOutputStream out = new FileOutputStream(utils.getPdfFileWithPath(bookId));
    FileChannel inChannel = in.getChannel();
    FileChannel outChannel = out.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    in.close();
    out.close();
}
 
开发者ID:OlegKlimenko,项目名称:Plamber-Android,代码行数:10,代码来源:UploadOfflineDialog.java

示例13: xferTest03

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Test
public void xferTest03() throws Exception { // for bug 4559072
    byte[] srcData = new byte[] {1,2,3,4} ;

    // get filechannel for the source file.
    File source = File.createTempFile("source", null);
    source.deleteOnExit();
    RandomAccessFile raf1 = new RandomAccessFile(source, "rw");
    FileChannel fc1 = raf1.getChannel();
    fc1.truncate(0);

    // write out data to the file channel
    int bytesWritten = 0;
    while (bytesWritten < 4) {
        bytesWritten = fc1.write(ByteBuffer.wrap(srcData));
    }

    // get filechannel for the dst file.
    File dest = File.createTempFile("dest", null);
    dest.deleteOnExit();
    RandomAccessFile raf2 = new RandomAccessFile(dest, "rw");
    FileChannel fc2 = raf2.getChannel();
    fc2.truncate(0);

    fc1.transferTo(0, srcData.length + 1, fc2);

    if (fc2.size() > 4)
        throw new Exception("xferTest03 failed");

    fc1.close();
    fc2.close();
    raf1.close();
    raf2.close();

    source.delete();
    dest.delete();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:38,代码来源:Transfer.java

示例14: transfer

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private static void transfer(FileChannel from, long position, long count, WritableByteChannel to) throws IOException {
    long maxCount = (64 * 1024 * 1024) - (32 * 1024);
    // Transfer data in chunks a bit less than 64MB
    // People state that this is a kind of magic number on Windows.
    // I don't care. The size seems reasonable.
    long offset = 0;
    while (offset < count) {
        offset += from.transferTo(position + offset, Math.min(maxCount, count - offset), to);
    }
}
 
开发者ID:lisnstatic,项目名称:live_master,代码行数:11,代码来源:MediaDataBox.java

示例15: transferToFully

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Transfers data from FileChannel using 
 * {@link FileChannel#transferTo(long, long, WritableByteChannel)}.
 * Updates <code>waitForWritableTime</code> and <code>transferToTime</code>
 * with the time spent blocked on the network and the time spent transferring
 * data from disk to network respectively.
 * 
 * Similar to readFully(), this waits till requested amount of 
 * data is transfered.
 * 
 * @param fileCh FileChannel to transfer data from.
 * @param position position within the channel where the transfer begins
 * @param count number of bytes to transfer.
 * @param waitForWritableTime nanoseconds spent waiting for the socket 
 *        to become writable
 * @param transferTime nanoseconds spent transferring data
 * 
 * @throws EOFException 
 *         If end of input file is reached before requested number of 
 *         bytes are transfered.
 *
 * @throws SocketTimeoutException 
 *         If this channel blocks transfer longer than timeout for 
 *         this stream.
 *          
 * @throws IOException Includes any exception thrown by 
 *         {@link FileChannel#transferTo(long, long, WritableByteChannel)}. 
 */
public void transferToFully(FileChannel fileCh, long position, int count,
    LongWritable waitForWritableTime,
    LongWritable transferToTime) throws IOException {
  long waitTime = 0;
  long transferTime = 0;
  while (count > 0) {
    /* 
     * Ideally we should wait after transferTo returns 0. But because of
     * a bug in JRE on Linux (http://bugs.sun.com/view_bug.do?bug_id=5103988),
     * which throws an exception instead of returning 0, we wait for the
     * channel to be writable before writing to it. If you ever see 
     * IOException with message "Resource temporarily unavailable" 
     * thrown here, please let us know.
     * 
     * Once we move to JAVA SE 7, wait should be moved to correct place.
     */
    long start = System.nanoTime();
    waitForWritable();
    long wait = System.nanoTime();

    int nTransfered = (int) fileCh.transferTo(position, count, getChannel());
    
    if (nTransfered == 0) {
      //check if end of file is reached.
      if (position >= fileCh.size()) {
        throw new EOFException("EOF Reached. file size is " + fileCh.size() + 
                               " and " + count + " more bytes left to be " +
                               "transfered.");
      }
      //otherwise assume the socket is full.
      //waitForWritable(); // see comment above.
    } else if (nTransfered < 0) {
      throw new IOException("Unexpected return of " + nTransfered + 
                            " from transferTo()");
    } else {
      position += nTransfered;
      count -= nTransfered;
    }
    long transfer = System.nanoTime();
    waitTime += wait - start;
    transferTime += transfer - wait;
  }
  
  if (waitForWritableTime != null) {
    waitForWritableTime.set(waitTime);
  }
  if (transferToTime != null) {
    transferToTime.set(transferTime);
  }
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:79,代码来源:SocketOutputStream.java


注:本文中的java.nio.channels.FileChannel.transferTo方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。