Java操作属性文件,支持新增或更新多个属性

Java操作属性文件。支持新增或更新多个属性

一、更新或新增单个属性的方法

/**
    * 写入properties信息
    * @param filePath  绝对路径(包含文件名称和后缀名)
    * @param parameterName  名称
    * @param parameterValue 值
    */
   public static void writeProperties(String filePath, String parameterName, String parameterValue) {
       
	   Properties props = new Properties();
       try {
        
           //假设文件不存在。创建一个新的
           File file=new File(filePath);
           if(!file.exists()){
	           file.createNewFile();
	       }
 
           InputStream fis = new FileInputStream(filePath);
           // 从输入流中读取属性列表(键和元素对)
           props.load(fis);
           fis.close();
           OutputStream fos = new FileOutputStream(filePath);
           props.setProperty(parameterName, parameterValue);
           // 以适合使用 load 方法载入到 Properties 表中的格式,
           // 将此 Properties 表中的属性列表(键和元素对)写入输出流
           props.store(fos, parameterName);
           fos.close(); // 关闭流
       } catch (IOException e) {
    	   System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");
       }
   }


二、更新或新增N个属性的方法

/**
    * @Title: writeMultiProperty
    * @Description: TODO(改动属性文件的多个属性)
    * @param filePath 属性文件路径(绝对路径)
    * @param list 要更新或新增的一列值
    * @return void  
    */
   public static void writeMultiProperty(String filePath, List<Pobj> list){
	   if(list == null || list.size() == 0) return;
	   
	   Properties props = new Properties();
       try {
           //假设文件不存在,创建一个新的
           File file=new File(filePath);
           if(!file.exists()){
	           file.createNewFile();
	       }
           InputStream fis = new FileInputStream(filePath);
           // 从输入流中读取属性列表(键和元素对)
           props.load(fis);
           fis.close();
           OutputStream fos = new FileOutputStream(filePath);
           
           // 设置属性
           for(Pobj obj : list){
               props.setProperty(obj.getKey(), obj.getValue());
           }
           
           // 保存至属性文件
           props.store(fos, "update properties");
           
           fos.close(); // 关闭流
       } catch (IOException e) {
    	   System.err.println("Visit "+filePath+" for updating THE PROPERTIES value error");
       }
   }

多个属性的更新或新增须要用到一个辅助类。暂时存储须要进行操作的值

/**
     * @ClassName: Pobj
     * @Description: TODO(辅助类,用来传递属性文件的每一条属性)
     * @author Bruce oiiopro@live.cn
     * @date 2014-11-18 下午11:31:00
     */
    public static class Pobj{
    	
    	private String key;
    	private String value;
    	
    	public Pobj(){}
    	
    	/**
    	 * <p>Title: </p>
    	 * <p>Description: </p>
    	 * @param key
    	 * @param value
    	 */
    	public Pobj(String key, String value){
    		this.key = key;
    		this.value = value;
    	}
    	
		public String getKey() {
			return key;
		}
		public void setKey(String key) {
			this.key = key;
		}
		public String getValue() {
			return value;
		}
		public void setValue(String value) {
			this.value = value;
		}
    	
    }


三、读取属性文件的方法

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SettingsJNWJ {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SettingsJNWJ.class);

	private static SettingsJNWJ instance;

	public Properties settings = new Properties();

	public SettingsJNWJ() {
		String filename = ("d:/jnwj.properties");
		LOGGER.info("Loading " + filename  + "...");
		InputStream stream = null;
		try {
			stream = new FileInputStream(filename);
			settings.load(stream);
			LOGGER.info( filename  + " loaded");
		} catch (IOException e) {
			LOGGER.error("Failed to  " + filename  , e);
		} finally {
			if(stream != null) IOUtils.closeQuietly(stream);
		}
	}

	public synchronized static SettingsJNWJ getInstance() {
		if (instance == null) {
			instance = new SettingsJNWJ();
		}

		return instance;
	}

	public String getString(String key) {
		return settings.getProperty(key);
	}
	
	public static void main(String[] args) {
		SettingsJNWJ s = SettingsJNWJ.getInstance();
		System.out.println(s.settings.toString());
//		System.out.println(SettingsJNWJ.getInstance().getString("uname"));
	}
}

附,属性文件内容 [ jnwj.properties ]

uname=wckj
upass=wckj123456
unitcode=2340958039458

四、測试

/**
	 * @Title: main
	 * @Description: TODO(这里用一句话描写叙述这种方法的作用)
	 * @param @param args    设定文件
	 * @return void    返回类型
	 * @throws
	 */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
//    	test1();
    	test2();
    }
    
    /**
     * @Title: 多个属性新增或更改的測试
     */
    public static void test2(){
    	List<Pobj> list = new ArrayList<Pobj>();
    	list.add(new Pobj("uname", "wckj"));
    	list.add(new Pobj("upass", "wckj123456"));
    	list.add(new Pobj("unitcode", "2340958039458"));
    	writeMultiProperty("D:/aiterw/conf/jnwj.properties", list);
        System.out.println(SettingsJNWJ.getInstance().settings.toString());
    }
    
    /**
     * @Title: 单个属性新增或更改的測试
     */
    public static void test1(){
        //写文件
        String passwork = "wckj123456";
        String jnwj = Settings.getInstance().getString("jnwj"); //这里能够直接写成自己的属性文件位置。 如:d:/jnwj.properties
        writeProperties(jnwj, "upass", passwork); 
 
        //从文件里取出userPassword,
        System.out.println(SettingsJNWJ.getInstance().getString("upass"));
    }






可以使用MyBatis的`<selectKey>`标签和`<insert>`标签来实现多个主键查询、不存在就新增、存在就更新的功能。 首先,定义一个Mapper接口,包含一个方法用于查询: ```java public interface MyMapper { MyEntity selectByKeys(@Param("key1") String key1, @Param("key2") String key2); } ``` 然后,在MyBatis的映射文件中,使用`<selectKey>`标签来查询数据,如果查询结果为空,则使用`<insert>`标签来新增数据,否则使用`<update>`标签来更新数据: ```xml <select id="selectByKeys" resultMap="myResultMap"> select * from my_table where key1 = #{key1} and key2 = #{key2} <selectKey keyProperty="key1" order="BEFORE"> select #{key1} from dual where not exists (select 1 from my_table where key1 = #{key1} and key2 = #{key2}) </selectKey> <selectKey keyProperty="key2" order="BEFORE"> select #{key2} from dual where not exists (select 1 from my_table where key1 = #{key1} and key2 = #{key2}) </selectKey> <insert id="insert" parameterType="MyEntity"> insert into my_table (key1, key2, value) values (#{key1}, #{key2}, #{value}) </insert> <update id="update" parameterType="MyEntity"> update my_table set value = #{value} where key1 = #{key1} and key2 = #{key2} </update> </select> ``` 在查询时,先调用`selectByKeys`方法,如果查询结果为空,则会先执行`<selectKey>`标签,判断数据是否存在,如果不存在,则会执行`<insert>`标签来新增数据,否则会执行`<update>`标签来更新数据。最终返回查询结果。 注意,`<selectKey>`标签必须放在`<select>`标签内部,且order属性必须设置为BEFORE,表示在执行查询之前执行。同时,keyProperty属性必须设置为实体类中对应主键的属性名,以便在新增更新时使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值