想了解properties资源文件操作工具类的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于project资源类型的相关问题,此外,我们还将为您介绍关于2-scala文件操作--自动关闭打开
想了解properties资源文件操作工具类的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于project资源类型的相关问题,此外,我们还将为您介绍关于2-scala文件操作--自动关闭打开的资源,读取properties文件、ajax读取properties资源文件数据、ajax读取properties资源文件数据的方法、Code片段 : .properties属性文件操作工具类 & JSON工具类的新知识。
本文目录一览:- properties资源文件操作工具类(project资源类型)
- 2-scala文件操作--自动关闭打开的资源,读取properties文件
- ajax读取properties资源文件数据
- ajax读取properties资源文件数据的方法
- Code片段 : .properties属性文件操作工具类 & JSON工具类
properties资源文件操作工具类(project资源类型)
import java.io.InputStream;
import java.util.Properties;
public class PropUtil
{
private static PropUtil instance = null;
private Properties props = null ;
private static String FILEPATH = "/config.properties";
private static synchronized PropUtil getInstatance(){
if(instance == null){
instance = new PropUtil();
}
return instance;
}
private PropUtil(){
loadProps();
}
private void loadProps() {
props = new Properties();
InputStream in = null;
try {
in = getClass().getResourceAsStream(FILEPATH);
props.load(in);
}
catch (Exception e) {
//此处可根据你的日志框架进行记录
System.err.println("Error reading conf properties in PropertyManager.loadProps() " + e);
e.printStackTrace();
}
finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
//此处可根据你的日志框架进行记录
}
}
}
private String getProp(String key) {
String value = props.getProperty(key);
return value == null ? "" : value.trim();
}
/**
* 根据key获取对应value
* @param key
* @return
*/
public static String getValue(String key){
return getInstatance().getProp(key);
}
/**
* 根据key获取对应value,如果为空则返回默认的value
* @param key
* @param defaultValue
* @return
*/
public static String getValue(String key,String defaultValue){
String value = getInstatance().getProp(key);
return "".equals(value) ? defaultValue : value;
}
}
2-scala文件操作--自动关闭打开的资源,读取properties文件
简介
使用scala的loan pattern自动关闭打开的资源
读取properties文件
依赖的jar
使用scala_arm库自动关闭资源文件时,需要引入以下依赖:
<dependency>
<groupId>com.jsuereth</groupId>
<artifactId>scala-arm_${scala.binary.version}</artifactId>
<version>1.4</version>
</dependency>
示例代码
import java.io.InputStream
import java.util.Properties
import scala.collection.JavaConversions.propertiesAsScalaMap
import resource.managed
import test.Control._
object Control {
def using[A <: { def close(): Unit }, B](resource: A)(f: A => B): B =
try {
f(resource)
} finally {
if (resource != null)
resource.close()
}
}
object FileOperator extends App {
val prop = new Properties()
//读取classpath下的配置文件
//读取properties文件
//使用scala_arm自动关闭打开的文件资源
for (
source <- managed(FileOperator.getClass.getClassLoader.getResourceAsStream("db.properties"))
) {
printProp(source)
}
//使用using自动关闭打开的文件资源
using(FileOperator.getClass.getClassLoader.getResourceAsStream("db.properties")) { source =>
{
printProp(source)
}
}
//使用绝对路径读取文件
val res = readTextFile("D:/scalawork/scala-learn/src/main/resources/db.properties")
res match {
case Some(lines) => lines.foreach(println)
case None => println("couldn''t read file")
}
//处理异常,返回Option
def readTextFile(filename: String): Option[List[String]] = {
try {
val lines = using(io.Source.fromFile(filename)) { source =>
(for (line <- source.getLines) yield line).toList
}
Some(lines)
} catch {
case e: Exception => None
}
}
//加载properties并转换为HashMap,读取其内容
def printProp(source: InputStream) = {
prop.load(source)
println(prop.getProperty("jdbc.idleMaxAge"))
prop.foreach(ele => {
println(s"${ele._1} => ${ele._2}")
})
}
}
ajax读取properties资源文件数据
- hello=englishww
- name=english zk
- emailEmpty=Field cannot be empty!
- emailInvalid=Invalid email address!
- $.ajax({
- type:'POST',
- dataType:'json',
- url:'/jeecms/jeecms/ajax/cms/getResourceBundle.do',
- async:false,
- success:function(data){
- jsonData=data.jsI18n;//jsI18n是java返回时赋予的名称
- jsi18n=eval_r('('+jsonData+')');//转化为json对象
- alert("property is "+jsi18n.hello);
- },
- error:function(data){
- alert("error");
- }
- });
- publicString getResourceBundle(){
- ResourceBundle RESOURCE_BUNDLE;
- if(contextPvd.getSessionAttr("gLanguage")!=null&&contextPvd.getSessionAttr("gLanguage").equals("1")){
- RESOURCE_BUNDLE=ResourceBundle.getBundle("jsI18n",Locale.ENGLISH);
- }else{
- RESOURCE_BUNDLE =ResourceBundle.getBundle("jsI18n",Locale.CHINA);
- }//判断语言类别的,忽视
- Set keySet=RESOURCE_BUNDLE.keySet();
- //读取资源文件数据拼接成json格式字符串返回
- String jsonString = newString();
- jsonString+="{";
- for(String key:keySet){
- jsonString+='"'+key+'"'+":"+'"'+RESOURCE_BUNDLE.getString(key)+'"'+",";
- }
- jsonRoot.put("jsI18n",jsonString.substring(0,jsonString.length()-1)+"}");
- return SUCCESS;
- }
ajax读取properties资源文件数据的方法
本文实例讲述了ajax读取properties资源文件数据的方法。分享给大家供大家参考。具体实现方法如下:
properties资源文件的内容如下:
hello=englishww name=english zk emailEmpty=Field cannot be empty! emailInvalid=Invalid email address!
js调用ajax处理代码:
$.ajax({ type:'POST',dataType:'json',url:'/jeecms/jeecms/ajax/cms/getResourceBundle.do',async:false,success:function(data){ jsonData=data.jsI18n;//jsI18n是java返回时赋予的名称 jsi18n=eval_r('('+jsonData+')');//转化为json对象 alert("property is "+jsi18n.hello); },error:function(data){ alert("error"); } });
java处理文件getResourceBundle.do代码:
publicString getResourceBundle(){ ResourceBundle RESOURCE_BUNDLE; if(contextPvd.getSessionAttr("gLanguage")!=null&&contextPvd.getSessionAttr("gLanguage").equals("1")){ RESOURCE_BUNDLE=ResourceBundle.getBundle("jsI18n",Locale.ENGLISH); }else{ RESOURCE_BUNDLE =ResourceBundle.getBundle("jsI18n",Locale.CHINA); }//判断语言类别的,忽视 Set keySet=RESOURCE_BUNDLE.keySet(); //读取资源文件数据拼接成json格式字符串返回 String jsonString = newString(); jsonString+="{"; for(String key:keySet){ jsonString+='"'+key+'"'+":"+'"'+RESOURCE_BUNDLE.getString(key)+'"'+","; } //把字符串赋给返回对象的jsI18n(这里随意) jsonRoot.put("jsI18n",jsonString.substring(0,jsonString.length()-1)+"}"); return SUCCESS; }
注意:js请求成功后,如果其它js里也要用到读出的内容,则把返回值赋给一个全局变量。
希望本文所述对大家的Ajax程序设计有所帮助。
Code片段 : .properties属性文件操作工具类 & JSON工具类
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “贵专” — 泥瓦匠
一、java.util.Properties API & 案例
java.util.Properties 是一个属性集合。常见的api有如下:
- load(InputStream inStream) 从输入流中读取属性
- getProperty(String key) 根据key,获取属性值
- getOrDefault(Object key, V defaultValue) 根据key对象,获取属性值需要强转
首先在resources目录下增加/main/resources/fast.properties:
fast.framework.name=fast fast.framework.author=bysocket fast.framework.age=1
然后直接上代码PropertyUtil.java:
/** * .properties属性文件操作工具类 * * Created by bysocket on 16/7/19. */ public class PropertyUtil { private static final Logger LOGGER = LoggerFactory.getLogger(PropertyUtil.class); /** .properties属性文件名后缀 */ public static final String PROPERTY_FILE_SUFFIX = ".properties"; /** * 根据属性文件名,获取属性 * * @param propsFileName * @return */ public static Properties getProperties(String propsFileName) { if (StringUtils.isEmpty(propsFileName)) throw new IllegalArgumentException(); Properties properties = new Properties(); InputStream inputStream = null; try { try { /** 加入文件名后缀 */ if (propsFileName.lastIndexOf(PROPERTY_FILE_SUFFIX) == -1) { propsFileName += PROPERTY_FILE_SUFFIX; } inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(propsFileName); if (null != inputStream) properties.load(inputStream); } finally { if ( null != inputStream) { inputStream.close(); } } } catch (IOException e) { LOGGER.error("加载属性文件出错!",e); throw new RuntimeException(e); } return properties; } /** * 根据key,获取属性值 * * @param properties * @param key * @return */ public static String getString(Properties properties, String key){ return properties.getProperty(key); } /** * 根据key,获取属性值 * * @param properties * @param key * @param defaultValue * @return */ public static String getStringOrDefault(Properties properties, String key, String defaultValue){ return properties.getProperty(key,defaultValue); } /** * 根据key,获取属性值 * * @param properties * @param key * @param defaultValue * @param <V> * @return */ public static <V> V getOrDefault(Properties properties, String key, V defaultValue){ return (V) properties.getOrDefault(key,defaultValue); } }
UT如下:
/** * {@link PropertyUtil} 测试用例 * <p/> * Created by bysocket on 16/7/19. */ public class PropertyUtilTest { @Test public void testGetProperties() { Properties properties = PropertyUtil.getProperties("fast"); String fastFrameworkName = properties.getProperty("fast.framework.name"); String authorName = properties.getProperty("fast.framework.author"); Object age = properties.getOrDefault("fast.framework.age",10); Object defaultVal = properties.getOrDefault("fast.framework.null",10); System.out.println(fastFrameworkName); System.out.println(authorName); System.out.println(age.toString()); System.out.println(defaultVal.toString()); } @Test public void testGetString() { Properties properties = PropertyUtil.getProperties("fast"); String fastFrameworkName = PropertyUtil.getString(properties,"fast.framework.name"); String authorName = PropertyUtil.getString(properties,"fast.framework.author"); System.out.println(fastFrameworkName); System.out.println(authorName); } @Test public void testGetOrDefault() { Properties properties = PropertyUtil.getProperties("fast"); Object age = PropertyUtil.getOrDefault(properties,"fast.framework.age",10); Object defaultVal = PropertyUtil.getOrDefault(properties,"fast.framework.null",10); System.out.println(age.toString()); System.out.println(defaultVal.toString()); } }
Run Console:
1 10 fast bysocket 1 10 fast bysocket
相关对应代码分享在 Github 主页
二、JACKSON 案例
首先,加个Maven 依赖:
<!-- Jackson --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-jaxrs</artifactId> <version>1.9.13</version> </dependency>
然后直接上代码JSONUtil:
/** * JSON 工具类 * <p/> * Created by bysocket on 16/7/19. */ public class JSONUtil { private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtil.class); /** * 默认JSON类 **/ private static final ObjectMapper mapper = new ObjectMapper(); /** * 将 Java 对象转换为 JSON 字符串 * * @param object * @param <T> * @return */ public static <T> String toJSONString(T object) { String jsonStr; try { jsonStr = mapper.writeValueAsString(object); } catch (Exception e) { LOGGER.error("Java Object Can''t covert to JSON String!"); throw new RuntimeException(e); } return jsonStr; } /** * 将 JSON 字符串转化为 Java 对象 * * @param json * @param clazz * @param <T> * @return */ public static <T> T toObject(String json, Class<T> clazz) { T object; try { object = mapper.readValue(json, clazz); } catch (Exception e) { LOGGER.error("JSON String Can''t covert to Java Object!"); throw new RuntimeException(e); } return object; } }
UT如下:
/** * {@link JSONUtil} 测试用例 * <p/> * Created by bysocket on 16/7/19. */ public class JSONUtilTest { @Test public void testToJSONString() { JSONObject jsonObject = new JSONObject(1, "bysocket", 33); String jsonStr = JSONUtil.toJSONString(jsonObject); Assert.assertEquals("{\"age\":1,\"name\":\"bysocket\",\"id\":33}", jsonStr); } @Test(expected = RuntimeException.class) public void testToJSONStringError() { JSONUtil.toJSONString(System.out); } @Test public void testToObject() { JSONObject jsonObject = new JSONObject(1, "bysocket", 33); String jsonStr = JSONUtil.toJSONString(jsonObject); JSONObject resultObject = JSONUtil.toObject(jsonStr, JSONObject.class); Assert.assertEquals(jsonObject.toString(), resultObject.toString()); } @Test(expected = RuntimeException.class) public void testToObjectError() { JSONUtil.toObject("{int:1}", JSONObject.class); } } class JSONObject { int age; String name; Integer id; public JSONObject() { } public JSONObject(int age, String name, Integer id) { this.age = age; this.name = name; this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public String toString() { return "JSONObject{" + "age=" + age + ", name=''" + name + ''\'''' + ", id=" + id + ''}''; } }
Run Console(抛出了异常信息):
16/07/19 23:09:13 ERROR util.JSONUtil: JSON String Can''t covert to Java Object! 16/07/19 23:09:13 ERROR util.JSONUtil: Java Object Can''t covert to JSON String!
三、小结
相关对应代码分享在 Github 主页 请看到的Java小伙伴多交流多评论改进之。 参考 黄勇 smart
如以上文章或链接对你有帮助的话,别忘了在文章结尾处评论哈~ 你也可以点击页面右边“分享”悬浮按钮哦,让更多的人阅读这篇文章。
我们今天的关于properties资源文件操作工具类和project资源类型的分享已经告一段落,感谢您的关注,如果您想了解更多关于2-scala文件操作--自动关闭打开的资源,读取properties文件、ajax读取properties资源文件数据、ajax读取properties资源文件数据的方法、Code片段 : .properties属性文件操作工具类 & JSON工具类的相关信息,请在本站查询。
本文标签: