package com.file.test; import java.io.File; /** * * @author xiaxr JAVA操作文件夹 */ public class FileServerTest { private boolean bool = false; private StringBuffer returnStr = new StringBuffer(); /** * 创建文件夹(不是根据路径级联创建,如果目录的上一级不存在就不能继续创建) */ public boolean CreateFileServer(String path) { File file = new File(path); // 判断文件夹是否存在,不存在就创建新文件夹 if (!file.isDirectory()) { bool = file.mkdir(); } return bool; } /** * 创建文件夹(根据路径级联创建,如果目录的上一级目录不存在则按路径创建) */ public boolean CreateFileServer2(String path) { // 根据符号"/"来分隔路径 String[] paths = path.split("/"); int length = paths.length; for (int i = 0; i < length; i++) { returnStr.append(paths[i]); File file = new File(returnStr.toString()); if (!file.isDirectory()) { bool = file.mkdir(); } returnStr.append("/"); } return bool; } /** * 删除指定路径所有文件和文件 */ public boolean delAllFile(String path) { File file = new File(path); if (file.exists()) { if(file.isDirectory()){ 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]);// 再删除空文件夹 } } }else if(file.isFile()){ file.delete(); } bool = true; } return bool; } /** * 删除文件夹 param folderPath 文件夹完整绝对路径 */ public boolean delFolder(String path) { try { delAllFile(path); // 删除完里面所有内容 File file = new File(path); if(file.isDirectory()){ bool = file.delete(); // 删除空文件夹 } } catch (Exception e) { e.printStackTrace(); } return bool; } /** * 删除文件夹(如果文件夹下面有文件或者子文件夹时就不会执行) */ public boolean deleteFileServer(String path) { File file = new File(path); // 判断文件夹是否存在 if (file.isDirectory()) { bool = file.delete(); } return bool; } /** * 读取文件夹下面所有文件夹和文件的内容 */ public void readFileServer(String path){ File file = new File(path); File[] tempList = file.listFiles(); String[] tempStr = file.list(); File temp = null; for(int i=0;i<tempList.length;i++){ temp = tempList[i]; if(temp.isFile()){ System.out.println("文件名:"+temp.getName()+" 文件路径:"+temp.getAbsolutePath()); }else if(temp.isDirectory()){ System.out.println("-----------------"); readFileServer(path+"/"+tempStr[i]); System.out.println("-----------------"); } } } /** * @param args */ public static void main(String[] args) { FileServerTest test = new FileServerTest(); // System.out.println(test.CreateFileServer("c:/11111/22222/444")); // System.out.println(test.CreateFileServer2("c:/11111/22222/333")); // System.out.println(test.deleteFileServer("c:/11111/22222/333")); // System.out.println(test.delFolder("c:/11111/22222/333")); //删除指定路径所有文件和文件 // System.out.println(test.delAllFile("c:/11111/22222")); test.readFileServer("c:/11111/22222"); } }