本案例采用第三方 jar 包完成,commons-io-2.5.jar,

这个 jar 对文件操作非常方便,大家可以尝试使用一下。

这里贴一个简单的 demo 供大家使用

import java.io.File;
import java.io.IOException; import org.apache.commons.io.FileUtils; public class MyFileUtils {
public static void main(String[] args) throws IOException { String srcPath = "F:/copyFile/src";
String destPath = "F:/copyFile/dest123";
copyFile(srcPath, destPath); // copyDirectory(srcPath, destPath);
// readFileToString(srcPath);
} // 创建文件夹
public static void makeDir(String destPath) {
File newFilePath = new File(destPath);
if (!newFilePath.exists()) {
newFilePath.mkdirs();
}
} // 复制文件夹及其内容
public static void copyDirectory(String srcPath, String destPath) throws IOException {
File file = new File(srcPath);
makeDir(destPath);
File destFile = new File(destPath);
FileUtils.copyDirectory(file, destFile);
} // 复制文件(应用场景:复制的同时更改文件名称)
public static void copyFile(String srcPath, String destPath) throws IOException {
File src = new File(srcPath);
makeDir(destPath);
File[] srcFiles = src.listFiles();
if (srcFiles.length > 0) {
for (File file : srcFiles) {
String filename = file.getName();
if (file.isDirectory()) {
copyFile(file.getAbsolutePath(), destPath);
}
if (filename.endsWith("html")) {
int index = filename.indexOf(".");
String newFileName = filename.substring(0, index) + "复制" + filename.substring(index);
File destFile = new File(destPath + "/" + newFileName);
FileUtils.copyFile(file, destFile);
}
}
}
} // 把文件 内容转成字符串
public static void readFileToString(String srcPath) throws IOException {
File src = new File(srcPath);
File[] srcFiles = src.listFiles();
if (srcFiles.length > 0) {
for (File file : srcFiles) {
String filename = file.getName();
if (file.isDirectory()) {
readFileToString(file.getAbsolutePath());
}
if (filename.endsWith("html")) {
String str = FileUtils.readFileToString(file, "utf-8");
System.out.println(str);
}
}
}
}
}

简单说明一下,

复制文件,包含文件夹 用到   FileUtils.copyDirectory(file, destFile);  

复制单个文件  FileUtils.copyFile(file, destFile);

把文件内容读取为字符串  FileUtils.readFileToString(file, "utf-8");

最新文章

  1. eayui datagrid 分页 排序 详解
  2. 爬虫初探(1)之urllib.request
  3. DVWA安装,ALMP环境搭建以及php版本转换
  4. Log4J日志管理类使用详解 (转)
  5. Java实现事件机制
  6. Objective-C Runtime(转)
  7. oracle数据库性能调优
  8. Android(java)学习笔记125:Clock app编写报错02
  9. 1105PHP笔记001
  10. LinuxCmd
  11. 【6】和作为连续序列s
  12. JAVA学习 分析Servlet
  13. Leetcode - 186 Reverse Words in a String II
  14. C# 鼠标事件弹框
  15. Use “error_messages” in Rails 3.2? (raises “undefined method” error)
  16. API 自动化框架
  17. day15
  18. css3 实现动画
  19. 《JavaScript设计模式与开发》笔记 5.关于正确写一个闭包
  20. Android SDK Manager详解

热门文章

  1. linux虚拟机安装值得注意的几点
  2. POI读word doc 03 文件的两种方法
  3. 函数的参数是函数,函数中Ajax返回的回调函数中的函数运行
  4. layuiadmin更新echarts
  5. LCD驱动分析(一)字符设备驱动框架分析
  6. Ubuntu 16.04如何使用无线网卡上网
  7. java excutors 四种类型的线程
  8. 4,list,list的列表嵌套,range
  9. 编辑器sublime(转)摘自网络
  10. Relay Race (DP)