Here you can find the source of copyFileUsingFileChannels(File source, File dest)
Parameter | Description |
---|---|
source | - source file |
dest | - target file |
Parameter | Description |
---|---|
IOException | an exception |
public static void copyFileUsingFileChannels(File source, File dest) throws IOException
//package com.java2s; /******************************************************************************* * Copyright (c) 2015 CA. All rights reserved. * * This source file is licensed under the terms of the Eclipse Public License 1.0 * For the full text of the EPL please see https://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class Main { /**/*from w w w . ja va 2 s . c om*/ * Copy a file * * @param source - source file * @param dest - target file * @throws IOException */ public static void copyFileUsingFileChannels(File source, File dest) throws IOException { FileInputStream inputStream = null; FileOutputStream outputStream = null; FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputStream = new FileInputStream(source); outputStream = new FileOutputStream(dest); if (inputStream != null) inputChannel = inputStream.getChannel(); if (outputStream != null) outputChannel = outputStream.getChannel(); if (outputChannel != null && inputChannel != null) outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } finally { safeFileChannelClose(inputChannel); safeFileChannelClose(outputChannel); safeFileInputStreamClose(inputStream); safeFileOutputStreamClose(outputStream); } } /** * Closes the file channel and releases any system resources associated with the stream. * * @param fc - reading streams of raw bytes */ public static void safeFileChannelClose(FileChannel fc) { if (fc != null) { try { fc.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Closes the file input stream and releases any system resources associated with the stream. * * @param fis - reading streams of raw bytes */ public static void safeFileInputStreamClose(FileInputStream fis) { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Closes the file output stream and releases any system resources associated with this stream * * @param fos - an output stream for writing data to a File */ public static void safeFileOutputStreamClose(FileOutputStream fos) { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }