java文件和目录的增删复制

发布时间 - 2026-01-11 01:54:29    点击率:

在使用java进行开发时常常会用到文件和目录的增删复制等方法。我写了一个小工具类。和大家分享,希望大家指正:

package com.wangpeng.utill;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * @author wangpeng
 * 
 */
public class ToolOfFile {

 /**
 * 创建目录
 * 
 * @param folderPath
 *      目录目录
 * @throws Exception
 */
 public static void newFolder(String folderPath) throws Exception {
 try {
  java.io.File myFolder = new java.io.File(folderPath);
  if (!myFolder.exists()) {
  myFolder.mkdir();
  }
 } catch (Exception e) {
  throw e;
 }
 }

 /**
 * 创建文件
 * 
 * @param filePath
 *      文件路径
 * @throws Exception
 */
 public static void newFile(String filePath) throws Exception {
 try {
  File myFile = new File(filePath);
  if (!myFile.exists()) {
  myFile.createNewFile();
  }
 } catch (Exception e) {
  throw e;
 }
 }

 /**
 * 创建文件,并写入内容
 * 
 * @param filePath
 *      文件路径
 * @param fileContent
 *      被写入的文件内容
 * @throws Exception
 */
 public static void newFile(String filePath, String fileContent)
  throws Exception {
 // 用来写入字符文件的便捷类
 FileWriter fileWriter = null;
 // 向文本输出流打印对象的格式化表示形式,使用指定文件创建不具有自己主动行刷新的新
 PrintWriter printWriter = null;
 try {
  File myFile = new File(filePath);
  if (!myFile.exists()) {
  myFile.createNewFile();
  }

  fileWriter = new FileWriter(myFile);
  printWriter = new PrintWriter(fileWriter);

  printWriter.print(fileContent);
  printWriter.flush();
 } catch (Exception e) {
  throw e;
 } finally {
  if (printWriter != null) {
  printWriter.close();
  }
  if (fileWriter != null) {
  fileWriter.close();
  }
 }
 }

 /**
 * 复制文件
 * 
 * @param oldPath
 *      被拷贝的文件
 * @param newPath
 *      复制到的文件
 * @throws Exception
 */
 public static void copyFile(String oldPath, String newPath)
  throws Exception {
 InputStream inStream = null;
 FileOutputStream outStream = null;
 try {
  int byteread = 0;
  File oldfile = new File(oldPath);
  // 文件存在时
  if (oldfile.exists()) {
  inStream = new FileInputStream(oldfile);
  outStream = new FileOutputStream(newPath);

  byte[] buffer = new byte[1444];
  while ((byteread = inStream.read(buffer)) != -1) {
   outStream.write(buffer, 0, byteread);
  }
  outStream.flush();
  }
 } catch (Exception e) {
  throw e;
 } finally {
  if (outStream != null) {
  outStream.close();
  }
  if (inStream != null) {
  inStream.close();
  }
 }
 }

 /**
 * 复制文件
 * @param inStream 被拷贝的文件的输入流
 * @param newPath 被复制到的目标
 * @throws Exception
 */
 public static void copyFile(InputStream inStream, String newPath)
  throws Exception {
 FileOutputStream outStream = null;
 try {
  int byteread = 0;
  outStream = new FileOutputStream(newPath);
  byte[] buffer = new byte[1444];
  while ((byteread = inStream.read(buffer)) != -1) {
  outStream.write(buffer, 0, byteread);
  }
  outStream.flush();
 } catch (Exception e) {
  throw e;
 } finally {
  if (outStream != null) {
  outStream.close();
  }
  if (inStream != null) {
  inStream.close();
  }
 }
 }

 /**
 * 复制目录
 * 
 * @param oldPath
 *      被复制的目录路径
 * @param newPath
 *      被复制到的目录路径
 * @throws Exception
 */
 public static void copyFolder(String oldPath, String newPath)
  throws Exception {
 try {
  (new File(newPath)).mkdirs(); // 假设目录不存在 则建立新目录
  File a = new File(oldPath);
  String[] file = a.list();
  File tempIn = null;
  for (int i = 0; i < file.length; i++) {
  if (oldPath.endsWith(File.separator)) {
   tempIn = new File(oldPath + file[i]);
  } else {
   tempIn = new File(oldPath + File.separator + file[i]);
  }

  if (tempIn.isFile()) {
   copyFile(tempIn.getAbsolutePath(),
    newPath + "/" + (tempIn.getName()).toString());
  } else if (tempIn.isDirectory()) {// 假设是子目录
   copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
  }
  }
 } catch (Exception e) {
  throw e;
 }
 }

 /**
 * 删除文件
 * 
 * @param filePathAndName
 */
 public static void delFileX(String filePathAndName) {
 File myDelFile = new File(filePathAndName);
 myDelFile.delete();
 }

 /**
 * 删除目录
 * 
 * @param path
 */
 public static void delForder(String path) {
 File delDir = new File(path);
 if (!delDir.exists()) {
  return;
 }
 if (!delDir.isDirectory()) {
  return;
 }
 String[] tempList = delDir.list();
 File temp = null;
 for (int i = 0; i < tempList.length; i++) {
  if (path.endsWith(File.separator)) {
  temp = new File(path + tempList[i]);
  } else {
  temp = new File(path + File.separator + tempList[i]);
  }

  if (temp.isFile()) {
  temp.delete();
  } else if (temp.isDirectory()) {
  // 删除完里面全部内容
  delForder(path + "/" + tempList[i]);
  }
 }
 delDir.delete();
 }

 public static void main(String[] args) {
 String oldPath = "F:/test/aaa/";
 String newPath = "F:/test/bbb/";

 try {
  // ToolOfFile.newFolder("F:/test/hello/");
  // ToolOfFile.newFile("F:/test/hello/world.txt","我爱你,the world!
");
  ToolOfFile.copyFolder(oldPath, newPath);
  // ToolOfFile.delForder("F:/test/hello");
 } catch (Exception e) {
  e.printStackTrace();
 }
 System.out.println("OK");
 }
}

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


# java文件目录增删复制  # java文件增删复制  # java目录增删复制  # java复制文件的4种方式及拷贝文件到另一个目录下的实例代码  # Java实现文件或文件夹的复制到指定目录实例  # java读取excel文件并复制(copy)文件到指定目录示例  # java怎么创建目录(删除/修改/复制目录及文件)代码实例  # java将一个目录下的所有数据复制到另一个目录下  # 不存在  # 写了  # 希望大家  # 大家分享  # 大家多多  # 小工具  # mkdir  # throw  # filePath  # catch  # exists  # void  # static  # newFolder  # myFolder  # String  # print  # printWriter  # flush  # close 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Laravel如何配置和使用缓存?(Redis代码示例)  Laravel怎么实现搜索功能_Laravel使用Eloquent实现模糊查询与多条件搜索【实例】  ,怎么在广州志愿者网站注册?  如何用ChatGPT准备面试 模拟面试问答与职场话术练习教程  Laravel distinct去重查询_Laravel Eloquent去重方法  Laravel广播系统如何实现实时通信_Laravel Reverb与WebSockets实战教程  如何彻底删除建站之星生成的Banner?  如何在云服务器上快速搭建个人网站?  网站制作大概多少钱一个,做一个平台网站大概多少钱?  如何在建站之星网店版论坛获取技术支持?  html5怎么画眼睛_HT5用Canvas或SVG画眼球瞳孔加JS控制动态【绘制】  UC浏览器如何切换小说阅读源_UC浏览器阅读源切换【方法】  宙斯浏览器文件分类查看教程 快速筛选视频文档与图片方法  为什么要用作用域操作符_php中访问类常量与静态属性的优势【解答】  高端企业智能建站程序:SEO优化与响应式模板定制开发  Laravel如何处理JSON字段_Eloquent原生JSON字段类型操作教程  Laravel如何配置中间件Middleware_Laravel自定义中间件拦截请求与权限校验【步骤】  详解jQuery停止动画——stop()方法的使用  如何解决hover在ie6中的兼容性问题  如何做网站制作流程,*游戏网站怎么搭建?  制作公司内部网站有哪些,内网如何建网站?  如何快速查询网站的真实建站时间?  如何快速生成橙子建站落地页链接?  如何用景安虚拟主机手机版绑定域名建站?  如何用5美元大硬盘VPS安全高效搭建个人网站?  如何自定义safari浏览器工具栏?个性化设置safari浏览器界面教程【技巧】  西安市网站制作公司,哪个相亲网站比较好?西安比较好的相亲网站?  北京企业网站设计制作公司,北京铁路集团官方网站?  如何在宝塔面板中修改默认建站目录?  如何实现javascript表单验证_正则表达式有哪些实用技巧  如何快速建站并高效导出源代码?  iOS发送验证码倒计时应用  夸克浏览器网页跳转延迟怎么办 夸克浏览器跳转优化  Laravel怎么配置.env环境变量_Laravel生产环境敏感数据保护与读取【方法】  通义万相免费版怎么用_通义万相免费版使用方法详细指南【教程】  b2c电商网站制作流程,b2c水平综合的电商平台?  Laravel如何使用Laravel Vite编译前端_Laravel10以上版本前端静态资源管理【教程】  Midjourney怎样加参数调细节_Midjourney参数调整技巧【指南】  Laravel项目结构怎么组织_大型Laravel应用的最佳目录结构实践  Gemini怎么用新功能实时问答_Gemini实时问答使用【步骤】  Laravel如何实现多语言支持_Laravel本地化与国际化(i18n)配置教程  Thinkphp 中 distinct 的用法解析  轻松掌握MySQL函数中的last_insert_id()  如何在服务器上三步完成建站并提升流量?  Win11怎么关闭透明效果_Windows11辅助功能视觉效果设置  悟空浏览器如何设置小说背景色_悟空浏览器背景色设置【方法】  如何在阿里云香港服务器快速搭建网站?  Laravel如何使用Passport实现OAuth2?(完整配置步骤)  Windows11怎样设置电源计划_Windows11电源计划调整攻略【指南】  Android自定义listview布局实现上拉加载下拉刷新功能