Java中File工具类--Java自学网

package com.util;

import java.io.File;

public class FileUtil {

 private static FileUtil instance = new FileUtil();
 
 public static FileUtil getInstance(){
  return instance;
 }
 
 public FileUtil() {
  // TODO Auto-generated constructor stub
 }


 
 /**
  * 删除文件
  * 
  * @param filePathAndName
  */
 public void delFile(String filePathAndName) {
  try {
   String filePath = filePathAndName;
   filePath = filePath.toString();
   File myDelFile = new File(filePath);
   myDelFile.delete();
  } catch (Exception e) {
   System.out.println("删除文件操作出错");
   e.printStackTrace();
  }
 }
 
 http://www.javalearns.com/

 /**
  * 删除文件夹
  * 
  * @param folderPath
  */
 public void delFolder(String folderPath) {
  try {
   delAllFile(folderPath);// 删除文件夹中所有的文件
   String filePath = folderPath;
   filePath = filePath.toString();
   File myFilePath = new File(filePath);
   myFilePath.delete();
  } catch (Exception e) {
   System.out.println("删除文件夹操作出错");
   e.printStackTrace();
  }
 }

 /**
  * 删除文件中的所有文件
  * 
  * @param folderPath
  */
 private void delAllFile(String path) {
  // TODO Auto-generated method stub
  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]);// 再删除空文件夹
   }
  }
 }

http://www.javalearns.com/

 /**
  * 测试删除功能
  * 
  * @param args
  */
 public static void main(String[] args) {

  String str = "E:\\test\\";
  File file = new File(str);
  //File fileb = new File("E:\test");
  FileUtil fp = new FileUtil();
  if (fp.deletedir(file)) {
   System.out.println("success");
  } else {
   System.out.println("failed!");
  }
 }

 /**
  * 删除文件
  * @param file
  * @return
  */
 public boolean deletefile(File f) {
  if (f.isFile())
   f.delete();
  return true;
 }

 /**
  * 删除目录
  * @param folder
  * @return
  */
 public boolean deletedir(File f) {
  if (f.isDirectory()) {
   File[] files = f.listFiles();
   if(files != null){
    for (int i = 0; i < files.length; i++) {
     if (files[i].isDirectory())
      deletedir(files[i]);
     else
      deletefile(files[i]);
    }
   }
  }
  f.delete();
  return true;

 }

}

文章转载自  http://www.javalearns.com/Html/?1561.html

更多Java学习文章请访问  Java免费学习网 http://www.javalearns.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值