上一节我们学习了读取properties文件中的信息这一节我们来往配置文件中写信息
程序代码如下
System.out.println("进来了");
String address = request.getParameter("address");
String port = request.getParameter("port");
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String dbname = request.getParameter("dbname");
String url = "jdbc:mysql://"+address+":"+port+"/"+dbname;
String path = request.getRealPath("");
// 数据库配置文件路径,这里要千万注意不要写相对路径,刚开始我就写的是src对应的路径,后来经过多次尝试终于找到原因了,必须写web-inf 下classes文件下的路径这样就是物理路径就正确了
String conPath1 = path+"\\WEB-INF\\classes\\com\\rhcy\\config\\db.properties";
String dbUrl = path+"\\WEB-INF\\classes\\com\\rhcy\\config\\lwz.sql";
File file = new File(conPath1);
try {
//创建文件
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Properties properties = new Properties();
try {
InputStream fis = new FileInputStream(conPath1);
try {
properties.load(fis);
} catch (IOException e) {
e.printStackTrace();
}
OutputStream fos = new FileOutputStream(conPath1);
properties.setProperty("driver","com.mysql.jdbc.Driver");
properties.setProperty("url",url);
properties.setProperty("username",username);
properties.setProperty("password",pass);
try {
properties.store(fos,null);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}