由于程序完成时,把这些值写在代码,将来更改起不方便。(而且容易忘记在代码中什么地方,哪个文件中时)所以,我们建议将这些值写入配置文件中。
今天就让我们一起来看看,在 JAVA 中对 properties 这种配置文件的操作吧。
1、properties 文件
#ParseZUrlNum.properties
#Tue Nov 15 11:52:15 CST 2005
nextnum=360
firstnum=73
secondnum=72
2、读写文件
{
ParseNZ pnz = new ParseNZ();
Properties properties = new Properties();
try {
File f = new File("ParseZUrlNum.properties");
properties = pnz.getProperties ("e:/work/product/src/com/yesky/productattribute/p/z/model/ParseZUrlNum.properties");
} catch (Exception e) {
e.printStackTrace();
}
String firstnum = properties.getProperty("firstnum");
String secondnum = properties.getProperty("secondnum");
String nextnum = properties.getProperty("nextnum");
int first=Integer.parseInt(firstnum);
int second=Integer.parseInt(secondnum);
int next=Integer.parseInt(nextnum);
System.out.println("firstnum=" + firstnum);
System.out.println("secondnum=" + secondnum);
System.out.println("nextnum=" + nextnum);
pnz.setProperties(first,second,next);
}
3、ParseNZ 类
public class ParseNZ{
Properties p = new Properties();
public Properties getProperties(String filename) throws IOException {
ClassLoader cl = this.getClass().getClassLoader();
FileInputStream input;
// if(cl!=null)
//input=cl.getResourceAsStream(filename);
input = new FileInputStream(filename);
//else
//input=ClassLoader.getSystemResourceAsStream(filename);
p.load(input);
return p;
}
public void setProperties(int first, int second, int next) {
p.setProperty("firstnum",String.valueOf(first));
p.setProperty("secondnum",String.valueOf(second));
p.setProperty("nextnum",String.valueOf(next));
File file = new File ("e:/work/product/src/com/yesky/productattribute/p/z/model/ParseZUrlNum.properties");
try {
OutputStream fos = new FileOutputStream(file);
p.store(fos, "ParseZUrlNum.properties");
fos.close();
} catch (FileNotFoundException ex) {
System.out.println("file is NULL !!!");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("IO is Error !!!");
ex.printStackTrace();
}
}
}
本例中地址是写死的。可改为如: File file = new File(System.getProperty("user.dir")
+ "/EMweb/WEB-INF/admininfo.properties");
这里面的关键是System.getProperty("user.dir") 返回当前工作目录。