java大文件复制:FileChannel

public static void  copyFile(String source, String target)throws Exception {

source = source.replace("\\", "/");

target = target.replace("\\", "/");

File source_file =new File(source);

File target_file =new File(target);

FileChannel in =null;

FileChannel out =null;

if (!source_file.exists() || !source_file.isFile()) {

throw new IllegalArgumentException(source_file +"文件不存在!");

}

File parent = target_file.getParentFile();

// 创建目标文件路径文件夹

if (!parent.exists()) {

parent.mkdirs();

}

// 判断目标文件是否存在

if (target_file.exists()) {

target_file.delete();

}

// 创建目标文件

if (!target_file.exists()) {

target_file.createNewFile();

}

FileInputStream inStream =null;

FileOutputStream outStream =null;

try {

inStream =new FileInputStream(source_file);

    outStream =new FileOutputStream(target_file);

    in = inStream.getChannel();

    out = outStream.getChannel();

    in.transferTo(0, in.size(), out);

}catch (IOException e) {

e.printStackTrace();

}finally {

inStream.close();

    in.close();

    outStream.close();

    out.close();

}

}


//main 测试

public static void main(String[] args) {

long l = System.currentTimeMillis();


    try {

          copyFile("D:\\test.txt", "D:\\tmp.txt");

    }catch (Exception e) {

e.printStackTrace();

    }

System.out.println("------------------");

    System.out.println(System.currentTimeMillis()-l);

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容