java读写ini或properties文件 原文件内容:a1=aaaa2=bbba3=ccca4=ddd我想把它改一条内容或多条内容,而且位置不变。我现在用的方法是把原文件内容读出来,然后新建一个同名文件,再把内容写进去。不过这样有点不好,有没有更好的方法。不新建文件。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 package com.ssnh.db;import com.mysql.jdbc.*;import java.io.*;import java.sql.*;import java.util.Properties;import javax.servlet.ServletContext;import javax.servlet.jsp.PageContext;public class DBConnection { private String userName = ""; private String password = ""; private String dataName = ""; private String serviceUrl = ""; private ServletContext pc = null; //private LinkedHashMap hm = null; private java.sql.Connection conn = null; public void init(ServletContext pc) { this.pc = pc; } public Exception connectionDB() { Exception ex = null; if(this.conn!=null) { return ex; } if(!this.getConfigPara()) { return new Exception("读取配置文件出错!"); } String url = "jdbc:mysql://"+serviceUrl+"/"+dataName+"?user="+userName+"&password="+password; try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); this.conn = DriverManager.getConnection(url); System.out.println("begin a connection"); } catch (Exception e) { ex = e; } return ex; } public java.sql.Connection getConn() { return conn; } public boolean closeConn() { if(this.conn!=null) { try { this.conn.close(); System.out.println("end a connection"); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } return true; } private boolean getConfigPara() { if(this.pc==null) { return false; } try { String fpath = pc.getRealPath("/")+"/conf/config.ini"; FileInputStream fis = new FileInputStream(fpath); Properties pp = new Properties(); pp.load(fis); this.serviceUrl = pp.get("serviceUrl").toString(); this.dataName = pp.get("dataName").toString(); this.userName = pp.get("username").toString(); this.password = pp.get("password").toString(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }} 1、properties 文件#ParseZUrlNum.properties#Tue Nov 15 11:52:15 CST 2005nextnum=360firstnum=73secondnum=722、读写文件{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"); 读写ini配置文件的类: import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 这是个配置文件操作类,用来读取和设置ini配置文件 * @author 由月 * @version 2004-08-18 */ public final class ConfigurationFile { /** * 从ini配置文件中读取变量的值 * @param file 配置文件的路径 * @param section 要获取的变量所在段名称 * @param variable 要获取的变量名称 * @param defaultValue 变量名称不存在时的默认值 * @return 变量的值 * @throws IOException 抛出文件操作可能出现的io异常 */ public static String getProfileString( String file, String section, String variable, String defaultValue) throws IOException { String strLine, value = ""; BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); boolean isInSection = false; try { while ((strLine = bufferedReader.readLine()) != null) { strLine = strLine.trim(); strLine = strLine.split("[;]")[0]; Pattern p; Matcher m; p = Pattern.compile("\\[\\s*.*\\s*\\]"); m = p.matcher((strLine)); if (m.matches()) { p = Pattern.compile("\\[\\s*" + section + "\\s*\\]"); m = p.matcher(strLine); if (m.matches()) { isInSection = true; } else { isInSection = false; } } if (isInSection == true) { strLine = strLine.trim(); String[] strArray = strLine.split("="); if (strArray.length == 1) { value = strArray[0].trim(); if (value.equalsIgnoreCase(variable)) { value = ""; return value; } } else if (strArray.length == 2) { value = strArray[0].trim(); if (value.equalsIgnoreCase(variable)) { value = strArray[1].trim(); return value; } } else if (strArray.length > 2) { value = strArray[0].trim(); if (value.equalsIgnoreCase(variable)) { value = strLine.substring(strLine.indexOf("=") + 1).trim(); return value; } } } } } finally { bufferedReader.close(); } return defaultValue; } /** * 修改ini配置文件中变量的值 * @param file 配置文件的路径 * @param section 要修改的变量所在段名称 * @param variable 要修改的变量名称 * @param value 变量的新值 * @throws IOException 抛出文件操作可能出现的io异常 */ public static boolean setProfileString( String file, String section, String variable, String value) throws IOException { String fileContent, allLine,strLine, newLine, reStr; String getValue; BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); boolean isInSection = false; fileContent = ""; try { while ((allLine = bufferedReader.readLine()) != null) { allLine = allLine.trim(); if (allLine.split("[;]").length > 1) reStr = ";" + allLine.split(";")[1]; else reStr = ""; strLine = allLine.split(";")[0]; Pattern p; Matcher m; p = Pattern.compile("\\[\\s*.*\\s*\\]"); m = p.matcher((strLine)); if (m.matches()) { p = Pattern.compile("\\[\\s*" + section + "\\s*\\]"); m = p.matcher(strLine); if (m.matches()) { isInSection = true; } else { isInSection = false; } } if (isInSection == true) { strLine = strLine.trim(); String[] strArray = strLine.split("="); getValue = strArray[0].trim(); if (getValue.equalsIgnoreCase(variable)) { newLine = getValue + " = " + value + " " + reStr; fileContent += newLine + "\r\n"; while ((allLine = bufferedReader.readLine()) != null) { fileContent += allLine + "\r\n"; } bufferedReader.close(); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, false)); bufferedWriter.write(fileContent); bufferedWriter.flush(); bufferedWriter.close(); return true; } } fileContent += allLine + "\r\n"; } }catch(IOException ex){ throw ex; } finally { bufferedReader.close(); } return false; } /** * 程序测试 */ public static void main(String[] args) { //String value = Config.getProfileString("sysconfig.ini", "Option", "OracleDB", "default"); //System.out.println(value); try { System.out.println(ConfigurationFile.setProfileString("d:/1.ini", "Settings", "SampSize", "111")); } catch (IOException e) { System.out.println(e.toString()); } } } java.util.Properties 并不能满足要求的,用这个类写进去的东西,位置会变掉的。 void compareProperties(String baseFile, String toCheckFile, String tempFile){ FileInputStream basefis = null ; FileInputStream toCheckfis = null; try { basefis = new FileInputStream(baseFile); toCheckfis = new FileInputStream(toCheckFile); } catch (FileNotFoundException e) { e.printStackTrace(); } Properties base = new Properties(); Properties toCheck = new Properties(); Properties temp = new Properties(); try { base.load(basefis); //#################读文件 toCheck.load(toCheckfis); } catch (IOException e) { e.printStackTrace(); } Set baseSet = base.keySet(); Iterator baseIter = baseSet.iterator(); int count = 0; int countLines = 0; while(baseIter.hasNext()){ Object key = baseIter.next(); countLines++; if(toCheck.containsKey(key)){ temp.setProperty((String)key,base.getProperty((String)key)); count++; } } FileOutputStream fos=null; try { fos = new FileOutputStream(tempFile); } catch (FileNotFoundException e) { e.printStackTrace(); } try { temp.store(fos,"baseFile:\t\t" + baseFile +"\n#toCheckFile:\t" + toCheckFile ); //##############写文件 System.out.println(" " + countLines + "lines checked and\n " + count + " lines found different and output to \n\t" + tempFile + "\n"); } catch (IOException e) { e.printStackTrace(); } } public class WMSPropertyFileReader { public static String INI_PROPERTY = "ini.properties"; public static String SERVER_CONFIG_PROPERTY = "server.conf"; private static WMSPropertyFileReader instance = null; private Map properties = null; /** Creates a new instance of WMSPropertyFileReader */ private WMSPropertyFileReader() { properties = new HashMap(); } /** * creates a singleton instance */ private static WMSPropertyFileReader getInstance(){ if(WMSPropertyFileReader.instance == null){ WMSPropertyFileReader.instance = new WMSPropertyFileReader(); } return WMSPropertyFileReader.instance; } /** * gets the Properties for the property type */ public static Properties getProperties(String property) throws ClientException { WMSPropertyFileReader propertyFileReader = null; Properties properties = null; try{ propertyFileReader = WMSPropertyFileReader.getInstance(); properties = (Properties) propertyFileReader.getProperties().get(property); if(properties == null){ properties = new Properties(); properties.load(new FileInputStream(property)); propertyFileReader.getProperties().put(property, properties); } }catch(Exception e){ throw new ClientException("EUE908",e); } return properties; } /** * caches all Property files. */ private Map getProperties() { return properties; } } java有Properties这个类,直接用就行了。 test.ini的内容就是楼主的内容,照楼主的意思写个不过地址好像变了 RandomAccessFile in = new RandomAccessFile("test.ini","rw"); String s1,s2 = new String(); while( (s1 = in.readLine()) != null){ if( s1.equals("a2=bbb")) s1 = "a2=change"; s2 += s1 + "\n"; } in.seek(0); in.writeBytes(s2); weiqiyiji(),这么改ini是不对的,ini是分段的,同一个ini中可能存在相同的行 Properties类,直接写位置会变,如果全列出来,需要把内容写进内存或临时文件,这样还是很复杂。如果量大一点,结果会怎么样?有没有更好的方法。再就是我只是举一个例子,实际应用当然不会这么小的文件。 public void propertiesFileTest(String str1,String str2,String str3,String str4) throws Exception { Properties properties = new Properties(); FileInputStream fileInput=new FileInputStream("e:/Test.properties"); properties.load(fileInput); properties.setProperty("a1", str1); properties.setProperty("a2", str2); properties.setProperty("a3", str3); properties.setProperty("a4", str4); OutputStream fileOutput=new FileOutputStream("e:/Test.properties"); properties.store(fileOutput, "TestProperties"); fileOutput.close(); } 要求不变位置。lirunjie1124() 你的方法就是把所有的属性键全列出来了。这样比较麻烦些。我没找到更好的方法,大家有吗?不一定非要用properties类。 位置一样是为了以后分析简单,还有个问题,注释文字也都需要带着。例如://a1的值。。a1=222aa//下面是//a2的值a2=3fs//a3a3=aaa properties乱不乱我没试过,不过ini应该是不乱的吧?而且楼主的需求有点古怪,其实对于这种常量的定义不一定非要采用文件的方式,你也可以采用java类或者DB的方式来存储.更好一点的和先进一点的就是用XML文件 properties与ini是一样的。XML与前两种也差不多,只不过是有格式而已。 properties,ini,xml差异大啦,怎么能是差不多呢?properties: key-valueini: section: key-valuexml: 树型结构xml难道修改了某一个节点的值之后它的顺序也会变?... xml位置当然不会变,我的意思是说在我这项目里,用到它们的功能是一样的,我只需要格式和内容而已。 我们也考虑了用xml,现在想确定的是用哪种方法更简单,更好一些。 我觉得一般情况下使用properties的配置文件都是不需要改变的,如果需要改变的话,我们可以使用xml配置文件,可以使用dom来修改xml,实现配置的动态话,可能要好用些. properties和ini本来就是常量文件,谁没事还老变来变去的?如果有变动需求,一般都应该保存到DB中.. 需要持久化的配置,我觉得还是使用xml的好点.如果确实有必要的话,也可以保存到数据库.不管怎么样 ,读写文件当然是很容易实现的. 不能下载中文文件名的文件 新手运算符“:”的问题,据说是JKD1.5新特性 新手求助!!! 誰知道BorderLayout橫向拖動的時候鼠標變成雙箭頭時侯怎么得到系統鼠標形狀? frame的左上角的图标怎么改变 关于用java写的递归函数的问题~~ [推荐]请不要做浮躁的人 ---------- 来自于matrix 怎样从控制台输入中读取汉字?? applet和RandomAccessFile的问题 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")出错 Lazy Load实现 this
import com.mysql.jdbc.*;
import java.io.*;
import java.sql.*;
import java.util.Properties;import javax.servlet.ServletContext;
import javax.servlet.jsp.PageContext;
public class DBConnection {
private String userName = "";
private String password = "";
private String dataName = "";
private String serviceUrl = "";
private ServletContext pc = null;
//private LinkedHashMap hm = null;
private java.sql.Connection conn = null; public void init(ServletContext pc)
{
this.pc = pc;
}
public Exception connectionDB()
{
Exception ex = null;
if(this.conn!=null)
{
return ex;
}
if(!this.getConfigPara())
{
return new Exception("读取配置文件出错!");
} String url = "jdbc:mysql://"+serviceUrl+"/"+dataName+"?user="+userName+"&password="+password;
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
this.conn = DriverManager.getConnection(url);
System.out.println("begin a connection");
} catch (Exception e) {
ex = e;
}
return ex;
} public java.sql.Connection getConn() {
return conn;
}
public boolean closeConn()
{
if(this.conn!=null)
{
try
{
this.conn.close();
System.out.println("end a connection");
return true;
}
catch (SQLException e)
{
e.printStackTrace();
return false;
}
}
return true;
}
private boolean getConfigPara()
{
if(this.pc==null)
{
return false;
}
try {
String fpath = pc.getRealPath("/")+"/conf/config.ini";
FileInputStream fis = new FileInputStream(fpath);
Properties pp = new Properties();
pp.load(fis);
this.serviceUrl = pp.get("serviceUrl").toString();
this.dataName = pp.get("dataName").toString();
this.userName = pp.get("username").toString();
this.password = pp.get("password").toString();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
#Tue Nov 15 11:52:15 CST 2005
nextnum=360
firstnum=73
secondnum=722、读写文件{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");
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 这是个配置文件操作类,用来读取和设置ini配置文件
* @author 由月
* @version 2004-08-18
*/
public final class ConfigurationFile {
/**
* 从ini配置文件中读取变量的值
* @param file 配置文件的路径
* @param section 要获取的变量所在段名称
* @param variable 要获取的变量名称
* @param defaultValue 变量名称不存在时的默认值
* @return 变量的值
* @throws IOException 抛出文件操作可能出现的io异常
*/
public static String getProfileString(
String file,
String section,
String variable,
String defaultValue)
throws IOException {
String strLine, value = "";
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
boolean isInSection = false;
try {
while ((strLine = bufferedReader.readLine()) != null) {
strLine = strLine.trim();
strLine = strLine.split("[;]")[0];
Pattern p;
Matcher m;
p = Pattern.compile("\\[\\s*.*\\s*\\]");
m = p.matcher((strLine));
if (m.matches()) {
p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
m = p.matcher(strLine);
if (m.matches()) {
isInSection = true;
} else {
isInSection = false;
}
}
if (isInSection == true) {
strLine = strLine.trim();
String[] strArray = strLine.split("=");
if (strArray.length == 1) {
value = strArray[0].trim();
if (value.equalsIgnoreCase(variable)) {
value = "";
return value;
}
} else if (strArray.length == 2) {
value = strArray[0].trim();
if (value.equalsIgnoreCase(variable)) {
value = strArray[1].trim();
return value;
}
} else if (strArray.length > 2) {
value = strArray[0].trim();
if (value.equalsIgnoreCase(variable)) {
value = strLine.substring(strLine.indexOf("=") + 1).trim();
return value;
}
}
}
}
} finally {
bufferedReader.close();
}
return defaultValue;
}
/**
* 修改ini配置文件中变量的值
* @param file 配置文件的路径
* @param section 要修改的变量所在段名称
* @param variable 要修改的变量名称
* @param value 变量的新值
* @throws IOException 抛出文件操作可能出现的io异常
*/
public static boolean setProfileString(
String file,
String section,
String variable,
String value)
throws IOException {
String fileContent, allLine,strLine, newLine, reStr;
String getValue;
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
boolean isInSection = false;
fileContent = "";
try {
while ((allLine = bufferedReader.readLine()) != null) {
allLine = allLine.trim();
if (allLine.split("[;]").length > 1)
reStr = ";" + allLine.split(";")[1];
else
reStr = "";
strLine = allLine.split(";")[0];
Pattern p;
Matcher m;
p = Pattern.compile("\\[\\s*.*\\s*\\]");
m = p.matcher((strLine));
if (m.matches()) {
p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
m = p.matcher(strLine);
if (m.matches()) {
isInSection = true;
} else {
isInSection = false;
}
}
if (isInSection == true) {
strLine = strLine.trim();
String[] strArray = strLine.split("=");
getValue = strArray[0].trim();
if (getValue.equalsIgnoreCase(variable)) {
newLine = getValue + " = " + value + " " + reStr;
fileContent += newLine + "\r\n";
while ((allLine = bufferedReader.readLine()) != null) {
fileContent += allLine + "\r\n";
}
bufferedReader.close();
BufferedWriter bufferedWriter =
new BufferedWriter(new FileWriter(file, false));
bufferedWriter.write(fileContent);
bufferedWriter.flush();
bufferedWriter.close();
return true;
}
}
fileContent += allLine + "\r\n";
}
}catch(IOException ex){
throw ex;
} finally {
bufferedReader.close();
}
return false;
}
/**
* 程序测试
*/
public static void main(String[] args) {
//String value = Config.getProfileString("sysconfig.ini", "Option", "OracleDB", "default");
//System.out.println(value);
try {
System.out.println(ConfigurationFile.setProfileString("d:/1.ini", "Settings", "SampSize", "111"));
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
FileInputStream basefis = null ;
FileInputStream toCheckfis = null;
try {
basefis = new FileInputStream(baseFile);
toCheckfis = new FileInputStream(toCheckFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Properties base = new Properties();
Properties toCheck = new Properties();
Properties temp = new Properties();
try {
base.load(basefis); //#################读文件
toCheck.load(toCheckfis);
} catch (IOException e) {
e.printStackTrace();
}
Set baseSet = base.keySet();
Iterator baseIter = baseSet.iterator();
int count = 0;
int countLines = 0;
while(baseIter.hasNext()){
Object key = baseIter.next();
countLines++;
if(toCheck.containsKey(key)){
temp.setProperty((String)key,base.getProperty((String)key));
count++;
}
}
FileOutputStream fos=null;
try {
fos = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
temp.store(fos,"baseFile:\t\t" + baseFile +"\n#toCheckFile:\t" + toCheckFile ); //##############写文件
System.out.println(" " + countLines + "lines checked and\n "
+ count + " lines found different and output to \n\t" + tempFile + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
public static String INI_PROPERTY = "ini.properties";
public static String SERVER_CONFIG_PROPERTY = "server.conf";
private static WMSPropertyFileReader instance = null;
private Map properties = null;
/** Creates a new instance of WMSPropertyFileReader */
private WMSPropertyFileReader() {
properties = new HashMap();
}
/**
* creates a singleton instance
*/
private static WMSPropertyFileReader getInstance(){
if(WMSPropertyFileReader.instance == null){
WMSPropertyFileReader.instance = new WMSPropertyFileReader();
}
return WMSPropertyFileReader.instance;
}
/**
* gets the Properties for the property type
*/
public static Properties getProperties(String property) throws ClientException {
WMSPropertyFileReader propertyFileReader = null;
Properties properties = null;
try{
propertyFileReader = WMSPropertyFileReader.getInstance();
properties = (Properties) propertyFileReader.getProperties().get(property);
if(properties == null){
properties = new Properties();
properties.load(new FileInputStream(property));
propertyFileReader.getProperties().put(property, properties);
}
}catch(Exception e){
throw new ClientException("EUE908",e);
}
return properties;
}
/**
* caches all Property files.
*/
private Map getProperties() {
return properties;
}
}
照楼主的意思写个
不过地址好像变了
RandomAccessFile in = new RandomAccessFile("test.ini","rw");
String s1,s2 = new String(); while( (s1 = in.readLine()) != null){
if( s1.equals("a2=bbb"))
s1 = "a2=change";
s2 += s1 + "\n";
}
in.seek(0);
in.writeBytes(s2);
{
Properties properties = new Properties();
FileInputStream fileInput=new FileInputStream("e:/Test.properties");
properties.load(fileInput);
properties.setProperty("a1", str1);
properties.setProperty("a2", str2);
properties.setProperty("a3", str3);
properties.setProperty("a4", str4);
OutputStream fileOutput=new FileOutputStream("e:/Test.properties");
properties.store(fileOutput, "TestProperties");
fileOutput.close();
}
例如:
//a1的值。。
a1=222aa//下面是
//a2的值
a2=3fs//a3
a3=aaa
而且楼主的需求有点古怪,其实对于这种常量的定义不一定非要采用文件的方式,你也可以采用java类或者DB的方式来存储.
更好一点的和先进一点的就是用XML文件
properties: key-value
ini: section: key-value
xml: 树型结构xml难道修改了某一个节点的值之后它的顺序也会变?...
如果有变动需求,一般都应该保存到DB中..
如果确实有必要的话,也可以保存到数据库.
不管怎么样 ,读写文件当然是很容易实现的.