Java中如何进行文件复制呢?
下文讲述文件复制的方法分享,如下所示:
实现思路: 借助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(); } } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。