栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java将一个目录下的所有文件复制n次

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java将一个目录下的所有文件复制n次

本文实例为大家分享了java将一个目录下的所有文件复制n次的具体代码,供大家参考,具体内容如下

1. 文件复制示意图

 

2.java程序

(1).调用

final static String SOURCESTRING = "/Users/amarao/360/download/test/";
final static String OUTPUTSTRING = "/Users/amarao/360/download/test4/";
 
 public static void main(String[] args) throws IOException {
 // 将SOURCESTRING下的文件复制3次到OUTPUTSTRING目录下
 LCopyFileUtils.copyFile(SOURCESTRING, OUTPUTSTRING, 3);
 }

(2).java工具类


public class LCopyFileUtils {
 
 
 public static boolean copyFile(String srcPath, String destPath, int count) throws IOException {
 File fileSrc = new File(srcPath);
 File[] files = fileSrc.listFiles();
 if (files == null) {
 System.out.println("Error:源文件夹下没有文件");
 return false;
 }
 for (int i = 0; i < files.length; i++) {
 if (files[i].isFile()) {
 File file = null;
 String fileName = files[i].getName();
 
 String filePrefix = fileName.substring(0, fileName.lastIndexOf("."));
 String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
 
 // 每个文件复制Count次
 for (int j = 0; j < count; j++) {
  file = new File(destPath + File.separator + filePrefix + "_" + i + "_" + j + fileSuffix);// 创建文件
  copyFileUsingFileChannels(files[i], file);
 }
 }
 }
 return true;
 }
 
 
 public static void copyFileUsingFileChannels(File srcFile, File destFile) throws IOException {
 FileChannel inputChannel = null;
 FileChannel outputChannel = null;
 try {
 inputChannel = new FileInputStream(srcFile).getChannel();
 outputChannel = new FileOutputStream(destFile).getChannel();
 outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
 System.out.println("复制文件成功:" + srcFile.getName() + " -> " + destFile.getName());
 } catch (Exception e) {
 System.out.println("Error:复制文件失败:" + srcFile.getName() + " -> " + destFile.getName());
 } finally {
 if (inputChannel != null) {
 inputChannel.close();
 }
 if (outputChannel != null) {
 outputChannel.close();
 }
 }
 }
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/137304.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号