- 我有一个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();
}
}
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.");
}
有关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;
}
希望这能有所帮助!!
查看Properties
类。它有一些可能有用的相关方法;
load()
save()
setProperty()
containsKey()