I have an assignment to create a java Swing application to do some stuff with a mysql database, I have planed to set the database connection properties in a .properties file. In that application user should be able to change the database properties through the application. The problem I’ve got is how to read and write a properties file through a swing application.
try {
Properties prop = new Properties();
//reading properties
FileInputStream in = new FileInputStream("conf/properties.xml");
prop.loadFromXML(in);
System.out.println(prop.getProperty("driver"));
in.close();
//Writing properties
FileOutputStream out = new FileOutputStream("conf/properties.xml");
prop.setProperty("username", "root");
prop.storeToXML(out, "rhym");
out.close();
} catch (Exception e) {
e.printStackTrace();
}
xml file..
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>database configuration</comment>
<entry key="driver">com.mysql.jdbc.Driver</entry>
<entry key="ip">127.0.0.1</entry>
<entry key="port">3306</entry>
<entry key="database">ofm_mnu_jvs</entry>
<entry key="username">user1</entry>
<entry key="password">123789</entry>
</properties>
Sounds like a program design exercise to me 🙂
First, you need to write code that can handle persisting Java’s
Propertiesobject to disk, and retrievingPropertiesfrom disk. You can do this in many ways, but the best way is to use Java Properties syntax to save the contents of thePropertiesobject to a user-editable text file. Your parser will just have to be smart enough to figure out how to read text from the file back into aPropertiesobject, but it’s really not that hard to do.Once your program is able to correctly read/write Java Properties syntax from files, you can write your User Interface to deal only with
Propertiesobject instances. The UI could tell your persistence objects/methods to save thePropertiesinstance each time the user changes a field or value.Bottom line is, it’s most important to figure out how to break up this program into smaller pieces. You could just as easily write a bunch of monolithic code that directly saves your properties files from ActionListeners in Swing, but none of that code would be reuseable. Break your code up into smaller objects (Parser object, UI object), then focus only on those smaller pieces, one at a time, until you can get them all working together to accomplish your goal.