本文实例为大家分享了java将一个目录下的所有文件复制n次的具体代码,供大家参考,具体内容如下
<强> 1。文件复制示意图强>
,
<强> 2. java程序强>
(1)。调用
最终的静态字符串SOURCESTRING="/用户/amarao/360/下载/测试/? 最终的静态字符串OUTPUTSTRING="/用户/amarao/360/下载/test4/? 公共静态void main (String [] args)抛出IOException {//将SOURCESTRING下的文件复制3次到OUTPUTSTRING目录下 LCopyFileUtils。拷贝文件(SOURCESTRING OUTPUTSTRING 3); }
(2)。java工具类
/* * * *参考: * Java将一个目录下的所有数据复制到另一个目录下:https://www.jb51.net/article/167726.htm * Java复制文件的4种方式:https://www.jb51.net/article/70412.htm * */公开课LCopyFileUtils {/* * *复制srcPath路径下的文件到destPath目录下 * * @param srcPath源文件路径 * @param destPath输出路径 * @param计数每个文件的复制次数 * @return是否复制成功 */srcPath公共静态逻辑拷贝文件(字符串,字符串destPath, int数)抛出IOException { fileSrc=https://www.yisu.com/zixun/new文件(srcPath); 文件[]文件=fileSrc.listFiles (); 如果(文件==null) { System.out.println(“错误:源文件夹下没有文件”); 返回错误; } for (int i=0;我& lt;files.length;我+ +){ 如果(文件[我].isFile ()) { 文件文件=零; 字符串文件文件名=[我]. getname (); 字符串filePrefix=文件名。substring (0, fileName.lastIndexOf (“。”); 字符串fileSuffix=fileName.substring (fileName.lastIndexOf (“。”);//每个文件复次制计数 for (int j=0;j & lt;计数;j + +) { 文件=新文件(destPath +文件。分离器+ filePrefix +“_”+我+“_”+ j + fileSuffix);//创建文件 [我]copyFileUsingFileChannels(文件,文件); } } } 返回true; }/* * *复制文件srcFile到destFile * * @param srcFile源文件 * @param destFile目的文件 */公共静态孔隙copyFileUsingFileChannels(文件srcFile文件destFile)抛出IOException { FileChannel inputChannel=零; FileChannel outputChannel=零; 尝试{ inputChannel=new FileInputStream (srcFile) .getChannel (); outputChannel=new FileOutputStream (destFile) .getChannel (); outputChannel。transferFrom (inputChannel 0 inputChannel.size ()); system . out。println(“复制文件成功:“+ srcFile.getName () +”→“+ destFile.getName ()); }捕捉(异常e) { system . out。println(“错误:复制文件失败:“+ srcFile.getName () +”→“+ destFile.getName ()); 最后}{ 如果(inputChannel !=null) { inputChannel.close (); } 如果(outputChannel !=null) { outputChannel.close (); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。