Use an INI File (Properties)
Java: How To
[INI file : user.ini] DBuser=anonymous
DBpassword=&8djsx
DBlocation=bigone
[JAVA code]
import java.util.*;
import java.io.*;
class readIni
{
public static void main(String args[])
{
readIni ini = new readIni();
ini.doit();
}
public void doit()
{
try
{
Properties p = new Properties();
p.load(new FileInputStream("user.ini"));
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 store method. This can be useful to store user prefenrences for example.
import java.util.*;
import java.io.*;
class WriteIni
{
public static void main(String args[])
{
WriteIni ini = new WriteIni();
ini.doit();
}
public void doit()
{
try
{
Properties p = new Properties();
p.load(new FileInputStream("user.ini"));
p.list(System.out);
// new Property
p.put("today", new Date().toString());
// modify a Property
p.put("DBpassword","foo");
FileOutputStream out = new FileOutputStream("user.ini");
p.store(out, "/* properties updated */");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
|
This ok with an application but you can't do it from an Applet since you can't write directly on the server without some kind of a server-side process.
To read an ini file via an Applet, the Properties class is still useful. Just load the Properties this way :
p.load((new URL(getCodeBase(), "user.ini")).openStream());
An INI file (or Properties) in a JAR can be used this way :
URL url = ClassLoader.getSystemResource("/com/rgagnon/config/system.ini");
if (url != null) props.load(url.openStream());
|