java项目读取以及写入properties文件

来源:互联网 发布:星巴克巧克力知乎 编辑:程序博客网 时间:2024/05/21 11:21

1,读

文件:
这里写图片描述

 public void read(){        Properties props = new Properties();        FileInputStream in = null;        try {            in = new FileInputStream("src/myPro.properties");            props.load(in);            String name = props.getProperty("name");            System.out.println(name);            in.close();        } catch (IOException e) {            System.out.println("文件找不着");        }    }

2,写入

写入分为几种
2.1 覆盖文件之前的数据

 public void write(){        Properties props = new Properties();        try {            OutputStream fos = new FileOutputStream("src/token.properties");            props.setProperty("mm","dd");            //这是给文件添加注释            props.store(fos, "update");            fos.close();        } catch (IOException e) {            System.out.println("文件找不着");        }    }

2.2 在文件上追加,这种情况无法更新,就是说如果以前有个key=1的数据,再添加一条key=1的,无法更新该数据,只能追加

 public void write(){        Properties props = new Properties();        try {            OutputStream fos = new FileOutputStream("src/token.properties",true);            props.setProperty("mm","dd");            //这是给文件添加注释            props.store(fos, "update");            fos.close();        } catch (IOException e) {            System.out.println("文件找不着");        }    }

2.3该方法可以在追加的同时,更新

public void write(){        Properties props = new Properties();        FileInputStream in = null;        try {            in = new FileInputStream("src/myPro.properties");            OutputStream fos = new FileOutputStream("src/token.properties");            props.load(in);            props.setProperty("mm","dd");            //这是给文件添加注释            props.store(fos, "update");            fos.close();        } catch (IOException e) {            System.out.println("文件找不着");        }    }
原创粉丝点击