创建properties文件保存在WEB项目的classes文件下

 1、保存数据

private synchronized boolean saveFile(String url,String filename){
        try {
            String path = servletRequest.getSession().getServletContext().getRealPath("/");
            System.out.println(path);
            path+="WEB-INF\\classes\\";
            File file = new File(path+filename);
            if(file.exists()){
                file.delete();
            }
            Properties prop = new Properties(); 
            prop.setProperty("username",dbusername);
            prop.setProperty("password",dbpassword);
            prop.setProperty("url",url);
            FileOutputStream fos = new FileOutputStream(file);
            prop.store(fos, null);
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
         
    }

 

2、读取数据

private synchronized String readFile(){
        String jsonString="{}";
        try {
            InputStream in = TestDbConnection.class.getClassLoader().getResourceAsStream(filenames[projectType]);
            if(in!=null){
                Properties properties = new Properties();
                properties.load(in);
                String nameString = properties.getProperty("username");
                String password = properties.getProperty("password");
                String vip = properties.getProperty("ip");
                String vdbname = properties.getProperty("dbname");
                String vtype = properties.getProperty("dbtype");
                jsonString="{username:\""+nameString+"\",password:\""+password+"\",ip:\""+vip+"\",dbname:\""+vdbname+"\",dbtype:\""+vtype+"\"}";
                System.out.println(" jsonString: "+jsonString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonString;
    }

 

posted @ 2013-10-24 15:08  若 ♂ 只如初见  阅读(373)  评论(0编辑  收藏  举报