添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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在根包找资源文件。

Android实验菜单的应用 android实验一

实验一  音乐播放器一、实验目的1、掌握Activity工作机制。2、掌握ListView、MediaPlayer等用法。二、实验内容设计一个音乐播放器,用ListView显示手机中MP3格式音乐,支持播放、暂停、继续、上一首、下一首等功能。 三、工作流程图 四、程序源代码1、布局页面在res的layout的activity_music.xml中 <?xml versio