深度遍历目录,读取properties文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
/**
* 在service中想获得action对应的package.properties中一个英文子串对应的中文
* 如:black.list.delete.ok={0}黑名单删除成功!
*
* @author chenhuiting
* @version 4.2.0
*/
public class LocalTextTools {
private static final Logger logger = Logger.getLogger(LocalTextTools.class);
private static final String propertiesFileName = "package.properties";
private static final String JOIN_REGEX = "#";
private static Map<String, String> properties = new HashMap<String, String>();
static {
try {
init();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void init() throws FileNotFoundException, IOException{
String basePath = LocalTextTools.class.getResource("/").getPath();
System.out.println(basePath);
File baseDir = new File(basePath);
LinkedList<File> stack = new LinkedList<File>();
stack.add(baseDir);
while (!stack.isEmpty()) {
File file = stack.remove();
if (file.isDirectory()) {
File[] subFiles = file.listFiles();
for (File subFile : subFiles) {
if (subFile.isDirectory()){
stack.add(subFile);
} else if (subFile.getName().equals(propertiesFileName)) {
String packagePathStr = subFile.getPath();
packagePathStr = packagePathStr.replaceFirst("^.*classes\\\\", "").replaceAll(propertiesFileName, "").replaceAll("\\\\", ".");
if (packagePathStr.lastIndexOf(".") == packagePathStr.length() - 1) {
packagePathStr = packagePathStr.substring(0, packagePathStr.length() - 1) + JOIN_REGEX;
}
Properties proObj = new Properties();
proObj.load(new FileInputStream(subFile));
for(Entry<Object, Object> entry : proObj.entrySet()){
String key = entry.getKey().toString();
String value = entry.getValue().toString();
properties.put(packagePathStr + key, value);
}
}
}
}
}
}
/*
* 这里的key指在properties文件中的key
* packagePath指propertie文件的那级package目录
* 如,com.baidu.union.cpro.web.admin下的package.properties中, black.list.delete.ok={0}黑名单删除成功!
* packagePath=com.baidu.union.cpro.web.admin
* key=black.list.delete.ok
* */
public static String getText(String packagePath, String key, Object... obj){
int i = 0;
String result = properties.get(packagePath + JOIN_REGEX + key);
if (obj != null){
for (Object object : obj){
result = result.replace("{"+ i +"}", object.toString());
i++;
}
}
return result;
}
/*
* 这里的key指在properties文件中的key
* packagePath指propertie文件的那级package目录
* 如,com.baidu.union.cpro.web.admin下的package.properties中, black.list.delete.ok={0}黑名单删除成功!
* packagePath=com.baidu.union.cpro.web.admin
* key=black.list.delete.ok
* */
public static String getText(String packagePath, String key){
return properties.get(packagePath + JOIN_REGEX + key);
}
}