java中Properties类的在javaee中的使用案例

先贴个项目目录

下面的东西就比较简单了,注释也写在代码中了,直接贴代码

这里要特别注意的是当我们运行程序写入properties文件的时候在项目中(Eclipse)的properties文件中是不可以看到操作的内容的,需要根据下面代码中的path路径在本地硬盘去找那个properties文件,真正的内容操作才可以看见的

     Properties prop = new Properties();
        //获取文件路径,此处获取文件路径的方法很多,这里贴了比较常见的一种方法
        String path = Thread.currentThread().getContextClassLoader().getResource("temp.properties").getPath();
        //创建输入流,用来根据key获取文件中的属性值
        /*InputStream in = new FileInputStream(path);
        prop.load(in);
        prop.getProperty("key");*/
        //穿件输出流,用来添加文件属性,而且需要添加的时候不能用load,而要用store()方法
        OutputStream out = new FileOutputStream(new File(path));
        //添加属性及属性值
        prop.setProperty("json", "123456789");
        prop.setProperty("json1", "12345678900");
        prop.setProperty("json2", "1234567890000");
        //用来根据key删除properties文件中的键值对,其中key跟value均被删除
        prop.remove("json1");
        //注意添加
        prop.store(out,"temp.properties");

 

 

 

当然写入可以用IO流来直接操作,比如下面的案例

String path = Thread.currentThread().getContextClassLoader().getResource("temp.properties").getPath();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path)), "GBK"));
        bw.write("json="+"wwwwwwwwwwwwwwwww");
        bw.flush();
        bw.close();

 

posted @ 2017-04-09 17:02  青春不打烊  阅读(469)  评论(0编辑  收藏  举报