键=值
这是我要插入和更新的java代码:
if (action.equals("insert")) {
if (con != null) {
if (key == null) {
//session.setAttribute(username, con);
out.println("****Connected Successfully****");
String rootPath=request.getSession().getServletContext().getRealPath("/");
System.out.println(rootPath);
String propPath=rootPath+"/WEB-INF/";
PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter(propPath+"importedDB.properties", true)));
out1.println(cname+"=jdbc:oracle:thin:@"+host+":"+port+"/"+service+","+username+","+password);
out1.close();
} else {
out.println("*Connection name "+cname+" already exists. Please try with another name");
}
}
}
if (action.equals("update")) {
if (con != null) {
if (key == null) {
out.println(cname+" is not available.");
} else {
String rootPath=request.getSession().getServletContext().getRealPath("/");
System.out.println(rootPath);
String propPath=rootPath+"/WEB-INF/";
PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter(propPath+"importedDB.properties", true)));
out1.println(cname+"=jdbc:oracle:thin:@"+host+":"+port+"/"+service+","+username+","+password);
out1.close();
out.println("updated successfully");
}
}
}
答案 0 :(得分:6)
加载它:
Properties properties = new Properties();
properties.load(your_reader);
然后使用remove()方法删除属性:
properties.remove(your_key);
最后将此更改写入文件属性文件:
properties.store(your_writer, null);
<强>更新强>
我在您发表评论后发布此更新:
我试过..得到的是什么,它不会打扰旧内容..只是用删除值重写文件..最初文件有key1 = value1和key2 = value2 ..使用上面的代码,我试过删除key2,现在文件有,key1 = value1 key2 = value2然后今天的时间和日期后key1 = value1
尝试使用此示例,我尝试过并且完美无缺,我认为如果代码无效,我会在代码中出现错误:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;
public class Props {
public Props() {
try {
File myFile = new File("props.properties");
Properties properties = new Properties();
properties.load(new FileInputStream(myFile));
properties.remove("deletethis");
OutputStream out = new FileOutputStream(myFile);
properties.store(out, null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[]args){
new Props();
}
}
props.properties 之前:
#Wed Mar 06 11:15:24 CET 2013
file=File
edit=Edit
deletethis=I'm gonna be deleted!
props.properties 之后:
#Wed Mar 06 11:15:24 CET 2013
file=File
edit=Edit
答案 1 :(得分:3)
你看过Apache Commons Configuration吗?
我会尝试类似的事情:
import org.apache.commons.configuration.PropertiesConfiguration;
PropertiesConfiguration config = new PropertiesConfiguration("myfile.properties");
config.clearProperty("my.property");
config.save();
答案 2 :(得分:0)
最简单,最明显的解决方案是读取输入文件,逐行检查并检查需要替换的属性。然后执行您需要的任何更改并重写整个文件。
您可能还想使用临时文件来编写新配置,然后用它替换现有配置。如果您的应用有可能在流程中间崩溃,这将有助于您。你仍然可以使用旧的配置。
答案 3 :(得分:0)
试
Properties props = new Properties();
FileInputStream in = new FileInputStream(file);
props.load(in);
in.close();
if (props.remove("key") != null) {
FileOutputStream out = new FileOutputStream(file);
props.store(out, "");
out.close();
}