这些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();
}
}
答案 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()