您的位置:首页 > 编程语言 > Java开发

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

2013-03-05 16:35 916 查看
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);

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: