文件工具类 —— FileUtil.java
- 获取Web工程的根目录 —— String getBasePath()方法
- 获取文件名称 —— public static String getFileName(String filePath)方法
- 获取文件名称前缀 —— public static String getPrefixOfFileName(String filePath)方法
- 获取文件名后缀(文件类型) —— public static String getFileType(String filePath)方法
import java.io.File;
public class FileUtil {
/**
* 函数功能:获取文件名称
*
* @param filePath 文件路径
* @return 文件名称
*/
public static String getFileName(String filePath) {
String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
return fileName;
}
/**
* 函数功能:获取文件名称的前缀
*
* @param filePath 文件路径
* @return 文件名称前缀
*/
public static String getPrefixOfFileName(String filePath) {
// 获取文件名称
String fileName = getFileName(filePath);
// 截取文件名称前缀
String prefixOfFileName = fileName.substring(0,fileName.lastIndexOf("."));
return prefixOfFileName;
}
/**
* 函数功能:获取文件名后缀(文件类型)
*
* @param filePath 文件路径
* @return 文件类型
*/
public static String getFileType(String filePath) {
// 获取文件名称
String fileName = getFileName(filePath);
// 截取文件名称前缀
String fileType = fileName.substring(fileName.lastIndexOf("."));
return fileType;
}
/**
* 函数功能:获取Web工程的根目录
*
* @return Web工程根目录
*/
public static String getBasePath() {
try {
String basePath = "";
String path = System.getProperty("user.dir");
File upload = new File(path);
if (!upload.exists()) {
upload.mkdirs();
}
basePath = upload.getAbsolutePath();
return basePath;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//测试
public static void main(String[] args) {
System.out.println("Web工程的根目录:"+getBasePath());
String filePath = "F:\\Java工具类\\文件操作工具类\\FileUtil.java";
System.out.println("文件名称为:"+getFileName(filePath));
System.out.println("文件名称前缀为:"+getPrefixOfFileName(filePath));
System.out.println("文件名称后缀为:"+getFileType(filePath));
}
}
/**
* 函数功能:根据文件路径加文件名读取文件内容
*
* @param fileName 文件路径加文件名称
* @return 文件内容字符串
*/
public static String readFileContent(String fileName) {
try {
File f = new File(fileName);
FileInputStream fip = new FileInputStream(f);
// 构建FileInputStream对象
InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
// 构建InputStreamReader对象,编码为UTF-8
StringBuffer sb = new StringBuffer();
while (reader.ready()) {
sb.append((char) reader.read());
// 转成char加到StringBuffer对象中
}
reader.close();
// 关闭读取流
fip.close();
// 关闭输入流,释放系统资源
return sb.toString();
} catch (IOException e) {
System.out.print(e.getMessage());
}
return null;
}
未完,待更新……