日期:2014-05-20  浏览次数:20790 次

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);