java中Properties理解

属性对象是哈希表的子类

不像地图键值对设置键和值的属性;

 例如:定义地图需要

Map<string,string> map=new Map <string,string>();

而化子性质直接定义对象,且他的键和值都是字符串类型的

Properties prop=new Properties();

1.设置键值对

         例如

prop.setProperty("123", "222");
prop.setProperty("789", "111");
prop.setProperty("456", "123");

2.读取键值对

prop.getProperty("123");
prop.getProperty("789");
prop.getProperty("456");

3.存储文件的两种方法

            

public static void WriterProperties() {
		Properties prop=new Properties();
		prop.setProperty("123", "222");
		prop.setProperty("789", "111");
		prop.setProperty("456", "123");
		Writer writer=null;
		try {
			/**
			 * list方法与store的方法区别
			 * list:带默认的注释,且提供printwriter和PrintStream两种方式写入
			 * store:自定义注释,且文件写入的时候写入了时间,提供OutputStream,Writer两种方法写入
			 */
			//list方法
			//PrintWriter pWriter=new PrintWriter(new FileWriter("prop.txt"));
			//PrintStream pStream=new PrintStream(new FileOutputStream("1.txt"));
			//prop.list(pStream);
			//store方法
			//OutputStream oStream=new FileOutputStream("1.txt",true);
			writer=new FileWriter("prop.txt",true);
			prop.store(writer, null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (writer!=null) {
				try {
					writer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}

4.读取文件中的属性中的值

             一.load方法

    • void load(InputStream inStream)

      从输入字节流读取属性列表(键和元素对)。

      void load(Reader reader)

      以简单的线性格式从输入字符流读取属性列表(关键字和元素对)。

	public static void readerProperties() {
		Properties prop=new Properties();
		InputStream inStream=null;
		//Reader reader=null;
		try {
			//创建一个读文件的对象
			//reader=new FileReader("prop.txt");
			inStream = new FileInputStream("porp.tst");
			//load方法是将文件的properties对象读到流中
			prop.load(inStream);
			//取properties中的key集合
			Set<Object> key=prop.keySet();
			//遍历set集合
			for (Object object : key) {
				String kString=(String) object;
				System.out.println(prop.getProperty(kString));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if (inStream!=null) {
				try {
					inStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

猜你喜欢

转载自blog.csdn.net/qq_35986709/article/details/84502357