读书人

java读写ini或properties资料

发布时间: 2011-12-03 22:57:58 作者: rapoo

java读写ini或properties文件
原文件内容:
a1=aaa
a2=bbb
a3=ccc
a4=ddd


我想把它改一条内容或多条内容,而且位置不变。我现在用的方法是把原文件内容读出来,然后新建一个同名文件,再把内容写进去。

不过这样有点不好,有没有更好的方法。不新建文件。

[解决办法]
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 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 ");

[解决办法]
java.util.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, remarkStr;
  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)
  remarkStr = "; " + allLine.split( "; ")[1];
  else
  remarkStr = " ";
  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 + " " + remarkStr;
  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;
}

}
[解决办法]
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);
[解决办法]
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();
}
[解决办法]
properties乱不乱我没试过,不过ini应该是不乱的吧?
而且楼主的需求有点古怪,其实对于这种常量的定义不一定非要采用文件的方式,你也可以采用java类或者DB的方式来存储.
更好一点的和先进一点的就是用XML文件
[解决办法]
properties,ini,xml差异大啦,怎么能是差不多呢?
properties: key-value
ini: section: key-value
xml: 树型结构

xml难道修改了某一个节点的值之后它的顺序也会变?...
[解决办法]
需要持久化的配置,我觉得还是使用xml的好点.
如果确实有必要的话,也可以保存到数据库.
不管怎么样 ,读写文件当然是很容易实现的.

读书人网 >J2SE开发

热点推荐