特点:支持Win、Unix文件路径;补充实现了Java IO File类中未实现的部分功能(非输入输出部分)
输入输出的工具类参见IOUtils:
NO.63 [file]IO常用工具类IOUtils(Java读文件、写文件、打Zip包)
目前功能:
- getFileName返回一个路径串的文件名部分;
- getFileNameWithoutPostfix返回一个路径串的文件名部分(无后缀);
- getFileType返回一个路径串的文件类型;
- getParentPath返回一个路径串的父目录路径;
- getMimeTypeByFileType根据文件类型返回其对应的MIME类型;
源码:
package amosryan.utility.file;
import java.io.File;
import java.util.Properties;
/**
* 文件常用功能(非输入输出部分)
* @author amosryan
* @since 2009.01.14
*/
public class FileUtils {
public static Properties mimeCastProp = new Properties();
static {
mimeCastProp.setProperty("DOC", "application/msword");
mimeCastProp.setProperty("XLS", "application/vnd.ms-excel");
mimeCastProp.setProperty("TXT", "text/plain");
mimeCastProp.setProperty("XML", "text/xml");
mimeCastProp.setProperty("PDF", "application/pdf");
}
/**
* 创建一个新文件
* @param newFile
* @throws Exception
*/
public static void createNewFile(File newFile) throws Exception {
File parent = newFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
newFile.createNewFile();
}
/**
* 获取一个文件的文件类型(取文件名中.后部分)
* @param filePath
* @return
*/
public static String getFileType(String filePath) {
filePath = getFileName(filePath);
int index = filePath.lastIndexOf('.');
if (index > -1) {
filePath = filePath.substring(index + 1);
}
return filePath;
}
/**
* 获取一个文件的文件名(无后缀,取文件名中.前部分)
* @param filePath
* @return
*/
public static String getFileNameWithoutPostfix(String filePath) {
int index = getFileName(filePath).lastIndexOf('.');
if (index > -1) {
filePath = filePath.substring(0, index);
}
return filePath;
}
/**
* 获取一个文件的文件名(取路径中最后的目录分隔符后部分)
* @param filePath
* @return
*/
public static String getFileName(String filePath) {
int index = filePath.lastIndexOf("/");
if (index > -1) {
filePath = filePath.substring(index + 1);
} else {
index = filePath.lastIndexOf("\\");
if (index > -1) {
filePath = filePath.substring(index + 1);
}
}
return filePath;
}
/**
* 获取目录串的父目录串
* @param dirPath
* @return
*/
public static String getParentPath(String dirPath) {
if(dirPath.endsWith("/")||dirPath.endsWith("\\")){
dirPath = dirPath.substring(0,dirPath.length()-1);
}
int index = dirPath.lastIndexOf("/");
if (index > -1) {
dirPath = dirPath.substring(0,index);
} else {
index = dirPath.lastIndexOf("\\");
if (index > -1) {
dirPath = dirPath.substring(0,index);
}
}
return dirPath;
}
/**
* 获取文件路径串的目录路径串
* @param filePath
* @return
*/
public static String getDirPath(String filePath) {
return getParentPath(filePath);
}
/**
* 根据文件类型返回其对应的MIME类型
* @param fileType
* @return
*/
public static String getMimeTypeByFileType(String fileType) {
String mimeType = mimeCastProp.getProperty(fileType.toUpperCase());
if (mimeType == null) {
mimeType = "application/x-msdownload";
}
return mimeType;
}
}