Java Propertiesファイルの読み込みと変更保存

6331 ワード

Propertiesファイルは、一般的に構成情報に使用されます.主な操作も読み込みです.
私のニーズは、変数の値をファイルに保存することです.次のプログラムの実行にも使います.もちろん普通のファイルで保存できます.
しかしpropertiesでこの値を保存したいです.
まとめ:
1.propertiesはhashtableで、キー値ペアを保存します.
2.propertiesはファイルから初期化し、値を変更して保存しないとファイルに影響しません.ファイルとは関係ありません.
3.propertiesはxmlまたはテキストとして保存できます
 
コード#コード#
package com.zk.util;



import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.URL;

import java.util.Properties;



public class PropertiesUtil {

    private static Properties properties= new Properties();

    

    /*properties   */

    private static final String PROPERTIES_FILE_NAME="ArticlePrimaryKey.properties";

    /* */

    private static final String KEY_LASTID="lastid";

    

    

    /**

     *    properties,     

     */

    private static void initProperties(){

        try {

            InputStream ips = PropertiesUtil.class.getResourceAsStream(PROPERTIES_FILE_NAME);

            properties.load(ips);

            ips.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }



    /**     properties,   "lastid"  

     * @return

     */

    public static int getPrimaryKey(){

        if(properties.isEmpty())//  properties  ,      。

            initProperties();

        return Integer.valueOf(properties.getProperty(KEY_LASTID)); //properties     String,     

    }

    

    /**  lastid  ,   

     * @param id

     */

    public static void saveLastKey(int id){

        if(properties.isEmpty())

            initProperties();

        //   

        properties.setProperty(KEY_LASTID, id+"");

        //    

        try {

            URL fileUrl = PropertiesUtil.class.getResource(PROPERTIES_FILE_NAME);//      

            FileOutputStream fos = new FileOutputStream(new File(fileUrl.toURI()));

            properties.store(fos, "the primary key of article table");

            fos.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    

    

    public static void main(String[] args) {

        System.out.println(getPrimaryKey());

        saveLastKey(1);

        

    }

}

 ArticlePrimaryKey.properties
#the primary key of article table

lastid=500

 
コメント:
1.propertiesファイルは、PropertiesUtilの同じパッケージの下に配置します.ロードと書き込みには、PropertiesUtilのクラスパスが使用されます.保存された変更ファイルは、プロジェクトbinの下にあるPropertiesUtilパッケージの下に表示されます.
2.ファイルをルートパッケージの下に置く場合.ファイルフローは
PropertiesUtil.class.getClassLoader().getResource(PROPERTIES_FILE_NAME);
つまりclassloaderにルートパッケージでリソースファイルを探させます.