【javaSE】常见对文件操作的工具类

本文介绍了几种实用的Java文件操作方法,包括读取properties配置文件、获取文件类型以及递归删除文件夹及其所有内容。这些方法简洁高效,适用于多种文件处理场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读取db.properties文件

/**
 * 读取properties配置文件
 * @return
 */
public static String readProperties(String fileName,String key){
	String value = "";
	InputStream in = null;
	try {
		Properties props = new Properties();
		in = FileUtil.class.getResourceAsStream(fileName);
		props.load(in);
		value = props.getProperty(key);
		
		
	} catch (IOException e) {
		e.printStackTrace();
		return "";
	}finally {
		try {
			in.close();
		} catch (IOException e) {
		}
	}
	
	return value;
}

获取文件类型

/**
 * 获取文件的类型。 文件名中最后一个"."后面的部分。
 * @param fileName
 * @return
 */
public static String getTypePart(String fileName){
	int point = fileName.lastIndexOf(".");
	String fileType = fileName.substring(point + 1);
	if (point == -1 || point == fileName.length() - 1) {
		return "无此类型";
	}
	return fileType;
}

删除文件夹以及文件夹下面的所有文件

/**
 * 删除文件夹以及下面的所有文件
 * @param delPath
 * @return
 */
public static boolean deleteFile(String delPath){
	try {
		File file = new File(delPath);
		if(!file.isDirectory()){
			file.delete();
		}else if(file.isDirectory()){
			
			String[] fileList = file.list();
			for(int i=0; i<fileList.length; i++){
				String tempFilePath = delPath + File.separator + fileList[i];
				File delFile = new File(tempFilePath);
				if(!delFile.isDirectory()){
					delFile.delete();
				}else{
					deleteFile(tempFilePath);
				}
			}
			if (file.listFiles().length <= 0) {
				file.delete();
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
	return true;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值