?? fileutil.java
字號:
/**
*
*/
package com.david.util;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
/**
* @author Administrator
*
*/
public class FileUtil implements IFileUtil{
/**
*
*/
public FileUtil() {
// TODO Auto-generated constructor stub
}
/**
* 創(chuàng)建一個新的目錄 如果創(chuàng)建成功返回這個新目錄 創(chuàng)建失敗就返回null
*
* @param file
* @return
*/
public File createFileDir(File file) {
File f;
if (file.exists()) {
// 路徑已經(jīng)存在
f = file;
} else {
// 路徑不存在
if (file.mkdirs()) {
// 如果創(chuàng)建成功
f = file;
} else {
// 創(chuàng)建失敗
f = null;
}
}
return f;
}
/**
* 獲取文件后綴名 并且改為小寫
*/
public String getFileSuffix(String fileName) {
String suffix;
suffix = fileName.trim().substring(fileName.trim().lastIndexOf(".") + 1)
.toLowerCase();
return suffix;
}
/**
* 改絕對路徑為相對路徑 注意是相對web應(yīng)用名字的路徑
*
* @param request
* @param path
* @return
*/
public String changePathToRelative(HttpServletRequest request,
String path) {
String relativePath = "";
String contextPath = request.getContextPath();
// 獲取該路徑在Web中的路徑
String webPath = path.substring(path.lastIndexOf(contextPath
.substring(1)));
// 從web路徑中獲取相對路徑
relativePath = webPath.substring(request.getContextPath().length());
return relativePath;
}
/**
* 構(gòu)造一個絕對路徑
*/
public File changePathToAbsol(HttpServletRequest request, String path){
return this.createFileDir(new File(request.getRealPath("")+changePath(path)));
}
/**
* 替換路徑中的/和\
*/
public String changePath(String path){
return path.replace("//", File.separator).replace("\\", File.separator);
}
/**
* 刪除一個文件,如果是目錄就刪除目錄和目錄下的所有文件
*/
public boolean deleteFile(File file){
boolean ok=true;
if(file.isFile()){
//文件
if(file.exists()){
file.delete();
}
}else if(file.isDirectory()){
//目錄,遞歸刪除
System.out.println(file.getName());
if(file.listFiles()==null||file.listFiles().length==0){
file.delete();
}else{
File[] f=file.listFiles();
for(int i=0;i<f.length;i++){
deleteFile(f[i]);
System.out.println(f[i].getName());
}
}
file.delete();
}
return ok;
}
/**
* @param args
*/
public void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("C://TEST//", "t.txt");
createFileDir(file);
System.out.print(deleteFile(file));
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -