Java中如何进行文件复制呢?

java-经验王 Java经验 发布时间:2021-09-25 10:16:21 阅读数:3208 1
下文讲述文件复制的方法分享,如下所示:
实现思路:
    借助FileInputStream对象和
	    FileOutPutStream对象即可进行文件的复制操作,如下所示:
例:
package com.java265.other;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class test {
	/*
	 * java265.com 复制文件的示例分享
	 */
	public static void main(String[] args) throws Exception {

		File a = new File("D:\\test.txt");
		File b = new File("D:\\test2.txt");
		copyFile(a, b);
	}

	public static void copyFile(File sourceFile, File destFile) throws IOException {
		if (!destfile.exists()) {
			destFile.createNewFile();
		}

		FileChannel source = null;
		FileChannel destination = null;

		try {
			source = new FileInputStream(sourceFile).getChannel();
			destination = new FileOutputStream(destFile).getChannel();
			destination.transferFrom(source, 0, source.size());
		} finally {
			if (source != null) {
				source.close();
			}
			if (destination != null) {
				destination.close();
			}
		}
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202109/16325362301233.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者