JavaSE文件操作工具類FileUtil詳解
更新時間:2019年08月30日 11:40:38 作者:謙玉
這篇文章主要為大家詳細介紹了JavaSE系列之文件操作工具類FileUtil,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了JavaSE文件操作工具類FileUtil的具體代碼,供大家參考,具體內(nèi)容如下
先展示一下文件工具類中打印文件夾樹形結(jié)構(gòu)的結(jié)果:

代碼如下:
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;
/**
* 練習(xí)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;
}*/
/**
* 創(chuàng)建文件/文件夾
* @param path 路徑
* @return 是否創(chuàng)建成功
* @throws Exception
*/
public static boolean creatFile(String path) throws Exception
{
if(null == path || path.length() == 0)
{
throw new Exception("路徑不正確!");
}
File file = new File(path);
//如果路徑存在,則不創(chuàng)建
if(!file.exists())
{
if(file.isDirectory())
{
//文件夾
file.mkdirs();
// file.mkdir(); 創(chuàng)建單層路徑 file.mkdirs() 可以創(chuàng)建多層路徑
return true;
}
else
{
//文件 先創(chuàng)建父路徑,然后再創(chuàng)建文件
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)
{
//循環(huán)遞歸刪除
for(File childFile:childFiles)
{
deleteFile(childFile.getAbsolutePath());
}
}
file.delete();
}
}
/**
* 獲取文件基本信息
* @param file
*/
public static void getBaseInfo(File file)
{
//文件絕對路徑 文件大小 文件是否是文件夾 文件是否是文件 文件是否可讀 文件是否可寫 文件是否可執(zhí)行 文件修改時間 文件父目錄名
//文件所在分區(qū)總大小 未使用大小 可用大小
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("文件所在分區(qū)大?。?+file.getTotalSpace()/1024/1024+"Mb");
System.out.println("文件所在分區(qū)未使用大?。?+file.getFreeSpace()/1024/1024+"Mb");
System.out.println("文件所在分區(qū)可用大小:"+file.getUsableSpace()/1024/1024+"Mb");
System.out.println("文件夾結(jié)構(gòu)如下圖:");
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);
}
}
}
}
}
/**
* 打印文件夾樹形結(jié)構(gòu)
* @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("文件不存在!");
}
//匿名內(nèi)部類實現(xiàn) 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表達式實現(xiàn)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();
}
}
}
/**
* 復(fù)制文件/文件夾及其中的所有子文件夾和文件
* @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 以后可以不關(guān)閉,可以自動關(guān)閉
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();
}
}
}
}
/**
* 復(fù)制指定地文件
* @return
*//*
public static boolean copyNamedFile()
{
}
*//**
* 剪切文件/文件夾及其中的所有子文件夾和文件
* @return
*/
public static void cutFile(String srcFilePath,String destFilePath)
{
//先復(fù)制,再刪除
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");*/
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- java自定義ClassLoader加載指定的class文件操作
- Java讀取OpenSSL生成的PEM公鑰文件操作
- java項目中讀取jdbc.properties文件操作
- java Spring Boot 配置redis pom文件操作
- Java使用BIO和NIO進行文件操作對比代碼示例
- java io讀取文件操作代碼實例
- Java IO流和文件操作實現(xiàn)過程解析
- Java RandomAccessFile基本文件操作示例
- Java中File文件操作類的基礎(chǔ)用法
- Java文件操作工具類fileUtil實例【文件增刪改,復(fù)制等】
- java IO 文件操作方法總結(jié)
- java文件操作之Path,Paths,Files
- java中的文件操作總結(jié)(干貨)
- Java字符流和字節(jié)流對文件操作的區(qū)別
- java文件操作工具類
- Java基礎(chǔ)之文件和目錄操作
相關(guān)文章
Java 對 Properties 文件的操作詳解及簡單實例
這篇文章主要介紹了Java 對 Properties 文件的操作詳解及簡單實例的相關(guān)資料,需要的朋友可以參考下2017-02-02
JAVA代碼設(shè)置selector不同狀態(tài)下的背景顏色
這篇文章主要介紹了JAVA代碼設(shè)置selector不同狀態(tài)下的背景顏色,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-05-05
JavaWeb?Servlet技術(shù)及其應(yīng)用實踐
這篇文章主要介紹了JavaWeb?Servlet技術(shù),Servlet指在服務(wù)器端執(zhí)行的一段Java代碼,可以接收用戶的請求和返回給用戶響應(yīng)結(jié)果,感興趣想要詳細了解可以參考下文2023-05-05
SpringBoot如何手寫一個starter并使用這個starter詳解
starter是SpringBoot中的一個新發(fā)明,它有效的降低了項目開發(fā)過程的復(fù)雜程度,對于簡化開發(fā)操作有著非常好的效果,下面這篇文章主要給大家介紹了關(guān)于SpringBoot如何手寫一個starter并使用這個starter的相關(guān)資料,需要的朋友可以參考下2022-12-12
idea中啟動項目彈出 IDEA out of memory窗口的解決方案
這篇文章主要介紹了idea中啟動項目彈出 IDEA out of memory窗口的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01

