Java实现复制一个目录下的所有文件
2016-05-22 22:18
786 查看
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; /* * 功能:将一个目录下的文件全部复制 * 新文件命名规则:原文件名+当前系统时间 * 同时输出复制总文件个数 * */ public class CopyFromSrcToDest { public static void main(String[] args) throws IOException{ File srcDir = new File("F://testcopy"); File src = null; File dest = null; String destPath = ""; Date date = new Date(); int count = 0; //判断是否是目录 if(srcDir.isDirectory()){ File[] files = srcDir.listFiles(); for(File file:files){ src = file; String wholefileName = src.getName(); //将文件名和文件后缀区分开来 int dotIndex = wholefileName.lastIndexOf("."); String fileName = wholefileName.substring(0, dotIndex); String fileExtend = wholefileName.substring(dotIndex); //规定复制文件的文件名 //此处用到了File.separator获取系统使用的文件路径分隔符,具有跨平台的优点 destPath = src.getParent()+ File.separator +fileName+"_" +date.toString().replace(":", "").replace(" ", "_")+fileExtend; System.out.println(destPath); dest = new File(destPath); dest.createNewFile(); FileInputStream fisSrc = new FileInputStream(src); FileOutputStream fosDest = new FileOutputStream(dest); byte[] by = new byte[1024]; int length; while((length = fisSrc.read(by)) != -1){ fosDest.write(by, 0, length); count++; } try{ if(fisSrc != null){ fisSrc.close(); } if(fosDest != null){ fosDest.close(); } }catch(Exception e){ e.printStackTrace(); } } System.out.println("总共复制了:"+ count +"个文件."); } } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树