Java中实现复制文件到文件,复制文件到文件夹,复制文件夹到文件,删除文件,删除文件夹,移动文件,移动文件夹的工具类

简介: package cn.edu.hactcm.cfcms.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.L

package cn.edu.hactcm.cfcms.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JOptionPane;

/**
 * CFMS :Computer files management system
 * version :1.0 2013-3-1 上午09:39:15
 */
public final class FileOperationUtils {
 /**
  * 创建单个文件
  *
  * @param path
  */
 public static void createFile(String path) {
  try {
   File file = new File(path);
   if (!file.exists()) {
    file.createNewFile();
    JOptionPane.showMessageDialog(null, "成功创建文件", "提示消息",
      JOptionPane.WARNING_MESSAGE);
   } else {
    file.delete();
    file.createNewFile();
    JOptionPane.showMessageDialog(null, "成功创建文件", "提示消息",
      JOptionPane.WARNING_MESSAGE);
   }
  } catch (Exception e) {
   JOptionPane.showMessageDialog(null, "创建文件失败", "提示消息",
     JOptionPane.WARNING_MESSAGE);
   e.printStackTrace();
  }
 }

 /**
  * 创建文件夹
  *
  * @param path
  */
 public static void createFolder(String path) {
  try {
   File file = new File(path);
   // 如果文件夹不存在那么就创建这个文件,如果文件文件夹存在
   if (!file.exists()) {
    file.mkdir();
    JOptionPane.showMessageDialog(null, "成功创建文件夹", "提示消息",
      JOptionPane.WARNING_MESSAGE);
   } else {
    file.delete();
    file.mkdir();
    JOptionPane.showMessageDialog(null, "成功创建文件夹", "提示消息",
      JOptionPane.WARNING_MESSAGE);
   }
  } catch (Exception e) {
   JOptionPane.showMessageDialog(null, "创建文件夹失败", "提示消息",
     JOptionPane.WARNING_MESSAGE);
   e.printStackTrace();
  }
 }

 /**
  * 将一个文件A拷贝给文件B
  *
  * @param from:要传递的文件A
  * @param theNewPath  :拷贝的目标文件B
  * @return
  */
 public static boolean copyFileToFile(String oldPath, String theNewPath) {
  File fromFile = new File(oldPath);
  File toFile = new File(theNewPath);
  FileInputStream fis = null;
  FileOutputStream fos = null;

  // 进行流操作
  try {
   fis = new FileInputStream(fromFile);
   fos = new FileOutputStream(toFile);
   int bytesRead;
   byte[] buf = new byte[4 * 1024];
   while ((bytesRead = fis.read(buf)) != -1) {
    fos.write(buf, 0, bytesRead);
   }
   fos.flush();
   fos.close();
   fis.close();
  } catch (Exception e) {
   System.out.println(e);
   return false;
  }
  // 如果拷贝成功,则返回真值。
  return true;
 }

 /**
  * 文件拷贝到文件夹内
  *
  * @param from:指定的文件
  * @param theNewPath  :指定的文件夹
  * @return
  */
 public static boolean copyFile2Folder(String oldPath, String theNewPath) {
  try {
   File fromFile = new File(oldPath);

   // 要复制到的新文件,如果不存在的话就创建这个文件
   String newPath = theNewPath + File.separator + fromFile.getName();
   File newToFile = new File(newPath);
   if (!newToFile.exists()) {
    newToFile.createNewFile();
   }

   // 通过流的方式复制文件
   FileInputStream fis = new FileInputStream(fromFile);
   FileOutputStream fos = new FileOutputStream(newToFile);
   int length;
   byte[] buf = new byte[4 * 1024];
   while ((length = fis.read(buf)) != -1) {
    fos.write(buf, 0, length);
   }
   fos.flush();
   fos.close();
   fis.close();
  } catch (Exception e) {
   System.out.println(e);
   return false;
  }
  return true;
 }

 // 如果前者是一个文件夹,后者是一个文件夹
 public static boolean copyFolder2Folder(String oldPath, String theNewPath) {
  try {
   File fromFile = new File(oldPath);
   File[] listFiles = fromFile.listFiles();
   // 文件夹的名字
   String fromFileFolderName = fromFile.getName();

   String newPath = theNewPath + File.separator + fromFileFolderName;
   File newFile = new File(newPath);
   if (!newFile.exists()) {
    newFile.mkdir();
   }

   for (int i = 0; i < listFiles.length; i++) {
    if (listFiles[i].isDirectory()) {
     // 文件夹复制到文件夹
     copyFolder2Folder(listFiles[i].getPath(), newPath);
    } else {
     // 文件复制到文件夹
     copyFile2Folder(listFiles[i].getPath(), newPath);
    }
   }
  } catch (Exception e) {
   System.out.println(e);
   return false;
  }
  return true;
 }

 /**
  * 统一控制文件拷贝的的内,这里相当于有了一个开关,符合条件的才可以打开这个开关
  *
  * @param from:任何文件或文件夹
  * @param theNewPath  :任何文件或文件夹
  */
 public static boolean copyFileInAllType(String oldPath, String theNewPath) {
  File fromFile = new File(oldPath);
  File toFile = new File(theNewPath);
  // 如果这两个地址都代表的是文件
  if (fromFile.isFile() && toFile.isFile()) {
   return copyFileToFile(oldPath, theNewPath);
  }

  // 如果前者是一个文件,后者是一个文件目录
  if (fromFile.isFile() && toFile.isDirectory()) {
   return copyFile2Folder(oldPath, theNewPath);
  }

  // 如果将一个文件夹复制给一个文件,这时候将出现错误。
  if (fromFile.isDirectory() && toFile.isFile()) {
   JOptionPane.showMessageDialog(null, "不能给一个文件夹复制给一个文件", "提示消息",
     JOptionPane.WARNING_MESSAGE);
   return false;
  }

  // 如果是一个文件夹复制到另外一个文件
  if (fromFile.isDirectory() && toFile.isDirectory()) {
   return copyFolder2Folder(oldPath, theNewPath);
  }
  return true;
 }

 /**
  * 打开文件夹,并显示所要显示的文件列表 这个方法可能出现访问异常的出现,但是不管是否有异常,都显示文件列表
  *
  * @param path
  */
 public static List<File> openFolder(String path) {
  File file = new File(path);
  List<File> files = new ArrayList<File>();
  try {
   if (file.exists()) {
    File[] listFiles = file.listFiles();
    for (File f : listFiles) {
     files.add(f);
    }
   }
  } catch (Exception e) {
   JOptionPane.showMessageDialog(null, e.getMessage());
   return null;
  }
  return files;
 }
 
 /**
  * 查找指定路径path下包含keyword关键字的文件列表
  * @param path     : 指定的目录
  * @param keyword  :关键字
  * @param files
  * @return
  */
 public static List<File> openFolder(String path,String keyword,ArrayList<File> files) {
  File file = new File(path);
  try {
   //首先判断这个文件是否存在,如果存在继续操作,如果不存在就返回空值
   if (file.exists()) {
    if (file.isFile()) {
     if (file.getName().contains(keyword)) {
      files.add(file);
     }
    } else {
     //如果文件夹的名称中包含关键字,那么就把这个文件添加到文件列表中
     if (file.getName().contains(keyword)) {
      files.add(file);
     }
     
     //不管文件夹是否包含关键字,都要继续操作这个文件夹内部的文件
     File[] listFiles = file.listFiles();
     //如果这个文件夹不是空的继续操作,如果是空的,返回现有的集合
     if (listFiles.length > 0) {
      for (File file2 : listFiles) {
       openFolder(file2.getPath(),keyword,files);
      }
     }
    }
   } else {//不管这个文件是否为空,都返回现有的文件集合
    return files;
   }
  } catch (Exception e) {
   e.printStackTrace();
   JOptionPane.showMessageDialog(null, "对不起,出错啦!");
   return null;
  }
  return files;
 }

 /**
  * 返回文件的信息
  *
  * @param files
  * @return
  */
 @SuppressWarnings("deprecation")
 public static Object[][] getFileInfo(List<File> files) {
  int fileNum = files.size();
  Object[][] fileInfos = new Object[fileNum][9];
  for (int row = 0; row < fileNum; row++) {
   // 获得文件名称
   fileInfos[row][0] = ((File) files.get(row)).getName();
   // 获取文件路径
   fileInfos[row][1] = ((File) files.get(row)).getPath();
   // 文件最后修改时间
   fileInfos[row][2] = new Date(((File) files.get(row)).lastModified())
     .toLocaleString();
   // 文件类型
   fileInfos[row][3] = FileInfoUtils.getFileSuffix(((File) files
     .get(row)).getPath());
   // 文件大小
   fileInfos[row][4] = FileInfoUtils.FormetFileSize(FileInfoUtils
     .getFileSize(((File) files.get(row)).getPath()));
   // 文件是否可读
   fileInfos[row][5] = ((File) files.get(row)).canRead();
   // 判断文件是否可写
   fileInfos[row][6] = ((File) files.get(row)).canWrite();
   // 判断文件是否可读
   fileInfos[row][7] = ((File) files.get(row)).setReadOnly();
   // 判断文件是否是隐藏文件
   fileInfos[row][8] = ((File) files.get(row)).setReadOnly();
  }
  return fileInfos;
 }

 /**
  * 删除文件
  * @param targetFile
  */
 public static void delFile(String targetFile) {
  try {
   String filePath = targetFile;
   File myDelFile = new File(filePath);
   myDelFile.delete();
  } catch (Exception e) {
   JOptionPane.showMessageDialog(null, "删除文件出错!", "错误提示",
      JOptionPane.ERROR_MESSAGE);
   e.printStackTrace();
  }
 }

 /**
  * 删除文件夹
  */
 public static void delFolder(String folderPath) {
  try {
   delAllFile(folderPath); // 删除完里面所有内容
   String filePath = folderPath;
   filePath = filePath.toString();
   java.io.File myFilePath = new java.io.File(filePath);
   myFilePath.delete(); // 删除空文件夹
  } catch (Exception e) {
   System.out.println("删除文件夹操作出错");
   e.printStackTrace();
  }
 }

 /**
  * 删除所有符合条件的文件
  * @param path
  */
 public static void delAllFile(String path) {
  File file = new File(path);
  if (!file.exists()) {
   return;
  }
  if (!file.isDirectory()) {
   return;
  }
  String[] tempList = file.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();
   }
   if (temp.isDirectory()) {
    delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
    delFolder(path + "/" + tempList[i]);// 再删除空文件夹
   }
  }
 }

 /**
  * 移动文件,删除原来的文件
  * @param oldPath
  * @param theNewPath
  */
 public static void moveFile(String oldPath, String theNewPath) {
  copyFileInAllType(oldPath, theNewPath);
  delFile(oldPath);
 }

 /**
  * 移动文件夹,然后删除文件夹
  * @param oldPath
  * @param theNewPath
  */
 public static void moveFolder(String oldPath, String theNewPath) {
  copyFileInAllType(oldPath, theNewPath);
  delFolder(oldPath);
 }
}

目录
相关文章
|
3天前
|
Java 开发者
Java一分钟之-Java IO流:文件读写基础
【5月更文挑战第10天】本文介绍了Java IO流在文件读写中的应用,包括`FileInputStream`和`FileOutputStream`用于字节流操作,`BufferedReader`和`PrintWriter`用于字符流。通过代码示例展示了如何读取和写入文件,强调了常见问题如未关闭流、文件路径、编码、权限和异常处理,并提供了追加写入与读取的示例。理解这些基础知识和注意事项能帮助开发者编写更可靠的程序。
14 0
|
4天前
|
Java
JDK环境下利用记事本对java文件进行运行编译
JDK环境下利用记事本对java文件进行运行编译
14 0
|
6天前
|
Arthas 安全 Java
java服务报错 FileNotFoundException:打开的文件过多
java服务报错 FileNotFoundException:打开的文件过多
15 0
|
10天前
|
Oracle Java 关系型数据库
windows 下 win11 JDK17安装与环境变量的配置(配置简单详细,包含IJ中java文件如何使用命令运行)
本文介绍了Windows 11中安装JDK 17的步骤,包括从官方网站下载JDK、配置环境变量以及验证安装是否成功。首先,下载JDK 17的安装文件,如果没有Oracle账户,可以直接解压缩文件到指定目录。接着,配置系统环境变量,新建`JAVA_HOME`变量指向JDK安装路径,并在`Path`变量中添加。然后,通过命令行(cmd)验证安装,分别输入`java -version`和`javac -version`检查版本信息。最后,作者分享了如何在任意位置运行Java代码,包括在IntelliJ IDEA(IJ)中创建的Java文件,只需去掉包声明,就可以通过命令行直接运行。
|
12天前
|
存储 监控 Java
如何在Java中实现等待文件修改后再读取数据的功能?
如何在Java中实现等待文件修改后再读取数据的功能?
18 0
|
XML JSON JavaScript
干货:排名前 16 的 Java 工具类!
在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类。以下工具类、方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码。
150 0
|
Java 数据安全/隐私保护 数据格式
干货:排名前16的Java工具类
image 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类。以下工具类、方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码。
4471 0
|
2天前
|
Java 调度
Java一分钟之线程池:ExecutorService与Future
【5月更文挑战第12天】Java并发编程中,`ExecutorService`和`Future`是关键组件,简化多线程并提供异步执行能力。`ExecutorService`是线程池接口,用于提交任务到线程池,如`ThreadPoolExecutor`和`ScheduledThreadPoolExecutor`。通过`submit()`提交任务并返回`Future`对象,可检查任务状态、获取结果或取消任务。注意处理`ExecutionException`和避免无限等待。实战示例展示了如何异步执行任务并获取结果。理解这些概念对提升并发性能至关重要。
16 5
|
2天前
|
安全 Java 调度
深入理解Java并发编程:线程安全与性能优化
【5月更文挑战第12天】 在现代软件开发中,多线程编程是提升应用程序性能和响应能力的关键手段之一。特别是在Java语言中,由于其内置的跨平台线程支持,开发者可以轻松地创建和管理线程。然而,随之而来的并发问题也不容小觑。本文将探讨Java并发编程的核心概念,包括线程安全策略、锁机制以及性能优化技巧。通过实例分析与性能比较,我们旨在为读者提供一套既确保线程安全又兼顾性能的编程指导。
|
2天前
|
Java
Java一分钟:线程协作:wait(), notify(), notifyAll()
【5月更文挑战第11天】本文介绍了Java多线程编程中的`wait()`, `notify()`, `notifyAll()`方法,它们用于线程间通信和同步。这些方法在`synchronized`代码块中使用,控制线程执行和资源访问。文章讨论了常见问题,如死锁、未捕获异常、同步使用错误及通知错误,并提供了生产者-消费者模型的示例代码,强调理解并正确使用这些方法对实现线程协作的重要性。
13 3