java将一个目录下的所有文件复制n次
时间:2021-02-20 09:11:20|栏目:JAVA代码|点击: 次
本文实例为大家分享了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工具类
/**
*
* 参考:
* Java将一个目录下的所有数据复制到另一个目录下:https://www.jb51.net/article/167726.htm
* Java复制文件的4种方式:https://www.jb51.net/article/70412.htm
* */
public class LCopyFileUtils {
/**
* 复制srcPath路径下的文件到destPath目录下
*
* @param srcPath 源文件路径
* @param destPath 输出路径
* @param count 每个文件的复制次数
* @return 是否复制成功
*/
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;
}
/**
* 复制文件srcFile到destFile
*
* @param srcFile 源文件
* @param destFile 目的文件
*/
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();
}
}
}
}
上一篇:Java内存映射 大文件轻松处理
栏 目:JAVA代码
本文标题:java将一个目录下的所有文件复制n次
本文地址:http://www.codeinn.net/misctech/66816.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




