从属性文件中获取值

时间:2013-02-22 11:54:37

标签: java file

  • 我有一个java代码将值附加到我的属性文件
  • 我的属性文件会有这样的条目。
  • key1 =主机,端口,orcl,用户名,密码
  • key2 =主机,端口,orcl,用户名,密码
  • key3 =主机,端口,orcl,用户名,密码等......

这些key1,key2和key3是连接名称。

  • 在进入属性文件之前,首先我必须检查文件是否已经给出连接名称条目。我的意思是,如果用户再次使用key1或key2或key3连接名称输入值,则必须发出提示,说明此连接名称可用,请尝试使用其他名称。

这是我的java代码,用于输入文件:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
       try
       {
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            con = DriverManager.getConnection("jdbc:oracle:thin:@"+host+":"+port+"/"+service,username,password);
            con.setAutoCommit(false);
            if (con!=null)
            {
                 session.setAttribute(username, con); 
                 out.println("Connected Successfully");          
                 PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter("my properties file", true)));
                 out1.println(cname+" = "+host+","+port+","+service+","+username+","+password);
                 out1.close();
            }
            else
            {
                 out.println("Error in getting connection");
            }
       }
       catch(Exception e)
       {
            e.printStackTrace();
       }
}

2 个答案:

答案 0 :(得分:4)

Properties prop = new Properties();
prop.load("pathToPropertiesFile");


String key; //This is the key which user will enter
String propKey = prop.getProperty(key);
if(propKey == null)
{
    // Key is not present so enter the key into the properties file
      prop.setProperty("keyName", key);
}
else
{
    // Throw error saying key already exists
      out.println("Key "+key+" already exists.");
} 

有关更多信息,请参阅Here以及有关Java中的属性的示例

<强>更新: 好的,如果你想检查这个值是否存在(无关)任何密钥,那么使用这个代码

   // Ignoring the loading of the properties file
   // Assuming properties file is loaded in "prop"
   Enumeration keySet = prop.keys();
   String key; // This is the key which user will enter
   boolean keyExists = false;
   while(keySet.hasMoreElements())
   {
       String keyName = (String) keySet.nextElement();
       String keyValue = prop.getProperty(keyName);
       if( key.equals(keyValue))  //Check against all the keys' value present
       {
           keyExists = true;
           break;
       }
   }

   if(keyExists)
   {
       //throw error
   }
   else
   {
       //insert key
   }

方法是获取所有密钥并检查其值。如果属性文件中存在的值与用户输入的值相同,则以其他方式知道要执行的操作

如果你想对KeyName进行检查,那么只需更改循环中的 if条件

if( key.equals(keyName))  //Check against all the key Name present in the properties file
{
 keyExists = true;
 break;
}

希望这会有所帮助!!

答案 1 :(得分:0)

查看Properties课程。它有一些可能有用的相关方法;

load()
save()
setProperty()
containsKey()