您的位置:首页 > 编程语言 > Java开发

Java Properties文件批量读取的工具方法

2017-02-09 11:14 357 查看
分享一下个人的经验代码:

package com.zhiwei.utils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
* Properties:本质是Map结构:保存key-value类型的键值对
* Properties文件载入工具类. 可载入多个properties文件,并将所有的
* properties属性文件的内容封装到一个Properties对象中,
* 给外界提供统一的访问接口(同名属性文件则会覆盖)
*
* 应用:作为应用类的内部组件使用(类似Tomcat的事件监听机制的Support)
*/
public class PropertiesUtil {

/**集成所有properties属性文件数据的封装类:Map*/
private static final Properties properties = new Properties();

/**文件名后缀*/
private static String suffix = ".properties";

/**已加载的资源文件绝对路径集合*/
private static List<String> alreadyLoadedFilePaths = new ArrayList<String>();

/**
* 获取封装所有properties文件数据的Properties对象
* @return
*/
public Properties getProperties() {
return properties;
}

/**
* 获取已加载的属性文件
* @return
*/
public List<String> getAlreayLoadedFilePaths(){
return alreadyLoadedFilePaths;
}

/**
* 加载指properties文件/目录下的properties文件
* @param file 加载的属性文件/目录路径
*/
public  boolean loadProperties(String file){

File basicFile = new File(file);
if(!basicFile.exists()){  //如果文件不存在则返回false
return false;
}

String basicFilePath = basicFile.getAbsolutePath();  //获取文件夹绝对路径(匹配系统)
FileInputStream fis = null;
//如果传入的是文件则判断是否properties文件,如果是则直接加载,否则false
if(basicFile.isFile()){
if(basicFile.getName().toLowerCase().contains(suffix)){
try {
fis = new FileInputStream(file);
properties.load(fis);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
alreadyLoadedFilePaths.add(basicFilePath);
return true;
}else{
return false;
}
}else{  //传入的是文件目录
boolean flag = false;  //判断文件夹中是否存在.properties文件
for(File tempFile:basicFile.listFiles()){
if(tempFile.getName().toLowerCase().contains(suffix)){
try {
fis = new FileInputStream(basicFilePath+File.separator+tempFile.getName());
properties.load(fis);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
alreadyLoadedFilePaths.add(basicFilePath+File.separator+tempFile.getName());
flag = true;
}
}
return flag;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息