栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

12、Properties文件操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

12、Properties文件操作

12、Properties文件操作

Properties(java.util.Properties)主要用于读取java的配置文件,各种语言都有自己所支配的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置
它提供了几种主要方法
1、getProperties(Sreing key),用指定的键在此属性列表中搜索属性,也就是通过参数key,得到key所对应的value。
2、**load(InputStream InStream),**从输入流中读取属性列表。通过对指定文件进行装载来获取文件中的所有键、值。以提供getProperty(String key)来搜索。
3、setProperty ( String key, String value),调用Hashtable的方法put。他通过调用基类的put方法来设置 键-值对。
4、**store ( OutputStream out, String comments),**以适合使用 load方法加载到 Properties表中的格式,将此Properties表中的属性列表(键和元素对)写入输出流。与load方法相反,该方法将键-值对写入到指定的文件中去。
5、**clear(),**清除所有装载的键-值对。该方法在基类中提供。

package IO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;



public class PropertiesDemo {
	
	public static String version="";
	public static String username="";
	public static String password="";
	//静态代码块,只执行一次
	static {
		//readConfig();
	}
	
	
	private static void writeConfig(String version,String username,String password) {
		Properties p=new Properties();
		p.put("app.version", version);
		p.put("db.username", username);
		p.put("db.password", password);
		try {
			
			//OutputStream out=new FileOutputStream("config.properties");
			OutputStream out=new FileOutputStream("config.properties");
			
			//写文件
			p.store(out, "update config");
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	private static void readConfig() {
		Properties p=new Properties();
		try {
			//配置文件在同一个包里,通过当前线程的类的加载器对象,来加载指定包下的配置文件
			//InputStream in=Thread.currentThread().getContextClassLoader().
			//  getResourceAsStream("IO/config.properties");
			
			//配置文件在同一个目录下
			InputStream in=new FileInputStream("config.properties");
			p.load(in);//加载文件
			
			//从properties中获取文件
			version=p.getProperty("aap.version");
			username=p.getProperty("db.usersion");
			password=p.getProperty("db.password");
			
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {

		//writeConfig("2", "vines", "120948");
		readConfig();
		System.out.println(PropertiesDemo.version);
		System.out.println(PropertiesDemo.username);
		System.out.println(PropertiesDemo.password);
	}

}

执行readConfig();

1
jhjh
1324

执行writeConfig(“2”, “vines”, “120948”);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/354246.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号