props or properties.
The structure is very similar to Windows INI file with except that there is no [...] section.
[Props file : user.props]
# this a comment ! this a comment too DBuser=anonymous DBpassword=&8djsx DBlocation=bigone
[JAVA code]
import java.util.*;
import java.io.*;
class ReadProps {
public static void main(String args[]) {
ReadProps props = new ReadProps();
props.doit();
}
public void doit() {
try{
Properties p = new Properties();
p.load(new FileInputStream("user.props"));
System.out.println("user = " + p.getProperty("DBuser"));
System.out.println("password = " + p.getProperty("DBpassword"));
System.out.println("location = " + p.getProperty("DBlocation"));
p.list(System.out);
}
catch (Exception e) {
System.out.println(e);
}
}
}Since the Properties class extends the Hashtable, we can manipulate the Properties through the get and put methods. The modified data can be saved back to a file with the save method. This can be useful to store user preferences for example. Note that the order is not preserved.
import java.util.*;
import java.io.*;
class WriteProps {
public static void main(String args[]) {
WriteProps props = new WriteProps();
props.doit();
}
public void doit() {
try{
Properties p = new Properties();
p.load(new FileInputStream("user.props"));
p.list(System.out);
// new Property
p.put("today", new Date().toString());
// modify a Property
p.put("DBpassword","foo");
FileOutputStream out = new FileOutputStream("user.props");
p.save(out, "/* properties updated */");
}
catch (Exception e) {
System.out.println(e);
}
}
}To read a Properties file via an Applet, load the Properties files this way :
p.load((new URL(getCodeBase(), "user.props")).openStream());
URL url =
ClassLoader.getSystemResource("/com/rgagnon/config/system.props");
if (url != null) props.load(url.openStream());
Written and compiled by Réal Gagnon ©1998-2005
[ home ]