這篇文章主要爲大家詳細介紹了JavaSE系列之文件操作工具類FileUtil,具有一定的參考價值,感興趣的小夥伴們可以參考一下
本文實例爲大家分享了JavaSE文件操作工具類FileUtil的具體代碼,供大家參考,具體內容如下
先展示一下文件工具類中打印文件夾樹形結構的結果:
代碼如下:
package com.mjq.iotest; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 練習File API * @author Administrator * */ public class FileUtil { /** * 單例模式 *//* private static FileUtil instance = null; private FileUtil() { } public static FileUtil getInstance() { synchronized (FileUtil.class) { if(null == instance) { instance = new FileUtil(); } } return instance; }*/ /** * 創建文件/文件夾 * @param path 路徑 * @return 是否創建成功 * @throws Exception */ public static boolean creatFile(String path) throws Exception { if(null == path || path.length() == 0) { throw new Exception("路徑不正確!"); } File file = new File(path); //如果路徑存在,則不創建 if(!file.exists()) { if(file.isDirectory()) { //文件夾 file.mkdirs(); // file.mkdir(); 創建單層路徑 file.mkdirs() 可以創建多層路徑 return true; } else { //文件 先創建父路徑,然後再創建文件 String dirPath = path.substring(0,path.lastIndexOf(File.separator)); File dirFile = new File(dirPath); if(!dirFile.exists()) { dirFile.mkdirs(); } File fileFile = new File(path); try { fileFile.createNewFile(); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { throw new Exception("文件已存在!"); } return false; } /** * 刪除文件/文件夾及其中的所有子文件夾和文件 * @return * @throws Exception */ public static void deleteFile(String filePath) throws Exception { if(null == filePath || filePath.length() == 0) { throw new Exception("filePath:"+filePath+"路徑不正確!"); } File file = new File(filePath); if(!file.exists()) { throw new Exception("filePath:"+filePath+"文件不存在!"); } if(file.isFile()) { file.delete(); } if(file.isDirectory()) { File [] childFiles = file.listFiles(); if(null != childFiles && childFiles.length!=0) { //循環遞歸刪除 for(File childFile:childFiles) { deleteFile(childFile.getAbsolutePath()); } } file.delete(); } } /** * 獲取文件基本信息 * @param file */ public static void getBaseInfo(File file) { //文件絕對路徑 文件大小 文件是否是文件夾 文件是否是文件 文件是否可讀 文件是否可寫 文件是否可執行 文件修改時間 文件父目錄名 //文件所在分區總大小 未使用大小 可用大小 System.out.println("文件基本信息如下:"); System.out.println("文件絕對路徑:"+file.getAbsolutePath()); System.out.println("文件名稱:"+file.getName()); System.out.println("文件大小:"+file.length()); System.out.println("文件是否是文件夾:"+file.isDirectory()); System.out.println("文件是否是文件:"+file.isFile()); System.out.println("文件是否可讀:"+file.canExecute()); System.out.println("文件是否可讀:"+file.canRead()); System.out.println("文件是否可寫:"+file.canWrite()); System.out.println("文件修改時間:"+file.lastModified()); System.out.println("文件父目錄名稱:"+file.getParent()); System.out.println("文件所在分區大小:"+file.getTotalSpace()/1024/1024+"Mb"); System.out.println("文件所在分區未使用大小:"+file.getFreeSpace()/1024/1024+"Mb"); System.out.println("文件所在分區可用大小:"+file.getUsableSpace()/1024/1024+"Mb"); System.out.println("文件夾結構如下圖:"); try { printFileStructure(file,1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 打印文件路徑 * @param file * @param deepth * @throws Exception */ public static void printFileStructure(File file ,int deepth) throws Exception { if(!file.exists()) { throw new Exception("文件路徑不存在!"); } if(!file.isHidden()) { if(file.isFile()) { //直接打印 printFile(file,deepth); return; } if(file.isDirectory()) { //先打印自身,然後遞歸打印子文件夾和子文件 printFile(file,deepth); File [] childFiles = file.listFiles(); if(null != childFiles && childFiles.length>0) { deepth++; for(File childFile : childFiles) { printFileStructure(childFile ,deepth); } } } } } /** * 打印文件夾樹形結構 * @param file * @param deepth */ public static void printFile(File file ,int deepth) { String name = file.getName(); StringBuffer sb = new StringBuffer(); StringBuffer tempSb = new StringBuffer(); for(int i =0;i<deepth;i++) { tempSb.append(" "); } sb.append(tempSb); sb.append("|"+"\n"); sb.append(tempSb); sb.append("------"+name); System.out.println(sb.toString()); } /** * 刪除特定的文件 * @return * @throws Exception */ public static void deleteNamedFile(String filePath,String regex) throws Exception { File file = new File(filePath); if(!file.exists()) { throw new Exception("文件不存在!"); } //匿名內部類實現 FilenameFilter 接口種的accept()方法,使用在正則表達式進行匹配 //accept(File dir,String name) 使用當前文件對象 和 當前文件的名稱 進行文件是否符合要求的標準判斷; /* ======================================================================================= File file = new File("."); String [] nameList = file.list((dir,name) -> name.endsWith(".java") || new File(name).isDirectory()); for(String name : nameList) { System.out.println(name); } ======================================================================================== 這裏使用Lamda表達式實現FilenameFilter 接口種的accept()方法 */ File[] fileList = file.listFiles(new FilenameFilter(){ /** * 使用正則表達式進行匹配 * @param regexStr * @return */ private boolean regexMatch(String name,String regexStr) { Pattern pattern = Pattern.compile(regexStr); Matcher matcher = pattern.matcher(name); return matcher.find(); } @Override public boolean accept(File dir, String name) { return regexMatch(name,regex); }}); if(null != fileList && fileList.length>0) { for(File filteredFile: fileList) { filteredFile.delete(); } } } /** * 複製文件/文件夾及其中的所有子文件夾和文件 * @return */ public static void copyFile(String srcFilePath,String destFilePath) { InputStream is = null; OutputStream os = null; try { if(creatFile(destFilePath)) { File srcFile = new File(srcFilePath); File destFile = new File(destFilePath); is = new FileInputStream(srcFile); os = new FileOutputStream(destFile); byte [] buffer = new byte[2048]; int temp = 0; while((temp = is.read(buffer))!=-1) { os.write(buffer, 0, temp); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { //java 7 以後可以不關閉,可以自動關閉 if(null != os) { try { os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(null != is) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * 複製指定地文件 * @return *//* public static boolean copyNamedFile() { } *//** * 剪切文件/文件夾及其中的所有子文件夾和文件 * @return */ public static void cutFile(String srcFilePath,String destFilePath) { //先複製,再刪除 try { copyFile( srcFilePath, destFilePath); deleteFile(srcFilePath); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 剪切文件/文件夾及其中的所有子文件夾和文件 * @return *//* public static boolean cutNamedFile() { } *//** * 文件壓縮 * @param destPath * @param fileFormats * @param srcFile * @return *//* public static boolean fileCompress(String destPath,String fileFormats,String srcFile,String regex) { } *//** * 文件解壓縮 * @param destPath * @param srcFile * @return *//* public static boolean fileDecompress(String destPath,String srcPath) { } *//** * 文件加密 * @param srcPath * @param destPath * @param encryptKey * @param encryptAlgorithm * @return *//* public static boolean fileEncrypt(String srcPath,String destPath,String encryptKey,String encryptAlgorithm) { } *//** * 文件解密 * @param srcPath * @param destPath * @param encryptKey * @param encryptAlgorithm * @return *//* public static boolean fileDecrypt(String srcPath,String destPath,String encryptKey,String encryptAlgorithm) { }*/ public static void main(String [] args) { File file = new File("D:\\北郵人下載\\書籍\\編譯原理"); getBaseInfo(file); try { /*deleteNamedFile("D:\\北郵人下載\\書籍",".pdf");*/ } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } /*cutFile("F:\\搶票軟件\\12306Bypass.exe","F:\\搶票軟件\\12306Bypass\\12306Bypass.exe");*/ } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。