这样格式的文件都是用Properties类来读取
解决方案 »
- jdbc连接SqlServer2008
- hibernate的核心问题?
- =====================各位老大,帮帮忙吧,我急死了,OpenId问题==========会php也要帮帮忙=====
- 求教一个JDBC的关于同一个Statement多次更新的问题!
- hibernate 查询 多个count如何取出
- 一个oracle表插入问题,望有兴趣的进来看看~~谢谢了
- 搞过J2EE实际项目的请进来,多谢!
- JDK1.4 字符串替换问题,请帮忙!!!~
- struts的验证框架validator的问题?在线等待,解决马上揭帖......
- 请教jBuilder9+Weblogic7的问题?
- 关于用java访问共享目录,恳请帮助,十万火急!!
- hibernate 一对一关系描述象这样怎么写?
如
QueryItem=Select Id,Name From $(Table)
Where Id=$(Id)
这种SQL语句读到程序中后,如何用实际值去代替Table和Id,且实际值的赋值如何做到一次赋值,多次使用?采用什么机制进行保存,是用hashtable吗?
tmpProps.load("x.ini");
String a=tmpProps.getProperty("key");
Properties tmpProps = new Properties();
tmpProps.load("x.ini");
String a=tmpProps.getProperty("key");
这样好象也不行吧
是错了,
tmpProps.load("x.ini");
应该是load(InputStream is);才对
InputStream tmpIs = Class.forName("xxx.java").getResourceAsStream("x.ini");
Properties tmpProps = new Properties();
tmpProps.load(tmpIs);
String a=tmpProps.getProperty("key");
xxx.java 与 x.ini在同一目录下
楼主参考一下下面的代码,吃饭时间搞出来的哟。
package lang.test;import java.util.*;
import java.io.*;
/**
* <title> IniReader
* <description>
* <company>
* @author Henryqqq
* @version 1.0
* @since 1.0
*
*2005-1-29 17:30:55
*/
public class IniReader
{
protected LinkedHashMap sections; //使用
public IniReader()
{
super();
sections = new LinkedHashMap();
}
public Map getSections()
{
return sections;
}
public Map getSection(String sectionName)
{
if(sections != null)
return (Map)sections.get(sectionName);
else
return null;
}
public void load(String fileName) throws FileNotFoundException
{
InputStream is = null;
try {
is = new FileInputStream(fileName);
load(is);
}catch (IOException e) {
e.printStackTrace();
}finally {
if(is!=null) try{ is.close(); } catch (IOException e1) {}
}
}
public void load(InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
String lastSectionName = null;
while( (line = reader.readLine()) != null)
{
line = line.trim();
if(line.startsWith("[") && line.endsWith("]"))
{
lastSectionName = line.trim().substring(1,line.length()-1);
sections.put(lastSectionName , new LinkedHashMap()); //创建一个section
}else if(line.length() == 0)
{
continue;
}else
{
if(lastSectionName!=null)
{
Map section = (Map)sections.get(lastSectionName);
int index = line.indexOf('=');
String key = index > 0 ? line.substring(0,index) : line; //如果没有等号,直接做key和value
String value = index > 0 ? line.substring(index +1) : line;
section.put(key,value);
}
}
}
}
public static void main(String[] args)
{
IniReader iniReader = new IniReader();
try
{
iniReader.load("F:/Projects/java/javaXTest/my.ini");
Map sections = iniReader.getSections();
Map section1 = (Map)sections.get("Section1");
System.out.println("key1:" + section1.get("Key1"));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
是用RandomAccessFile弄的
当然也是一行一行readLine主要是修改的时候用到文件指针所以用RandomAccessFile找的时候是
IniTool.get("Section1/key1");
写的时候也类似是可以用属性类型
但是[Section1]会当是key值, 不相信的你测试一下 打印所有的Property
package com.coscon.util;import java.io.*;/**
* An interface to a storage mechanism for making properties settings
* persistent. The store manages a collection of key/value pairs.
* The key must be a string and the values can be either, strings or
* array of strings. Convenience API to convert primitive
* types to strings is provided.
* This class is copied from <link>org.eclipse.jface.dialogs.IDialogSettings</link>.
* This interface can be treated as <link>java.util.Properties</link> plus.
* @author Chen Jipeng
* @version $Revision: 1.2 $ $Date: 2004/06/15 08:06:24 $
*/
public interface IPropertiesSettings {
/**
* Create a new section in the receiver and return it.
*
* @param name the name of the new section
* @return the new section
*/
public IPropertiesSettings addNewSection(String name);
/**
* Add a section in the receiver.
*
* @param section the section to be added
*/
public void addSection(IPropertiesSettings section);
/**
* Returns the value of the given key in this dialog settings.
*
* @param key the key
* @return the value, or <code>null</code> if none
*/
public String get(String key);
/**
* Returns the value, an array of strings, of the given key in
* this dialog settings.
*
* @param key the key
* @return the array of string, or <code>null</code> if none
*/
public String[] getArray(String key);
/**
* Convenience API.
* Convert the value of the given key in this dialog settings
* to a boolean and return it.
*
* @param key the key
* @return the boolean value, or <code>false</code> if none
*/
public boolean getBoolean(String key);
/**
* Convenience API.
* Convert the value of the given key in this dialog settings
* to a double and return it.
*
* @param key the key
* @return the value coverted to double, or throws <code>NumberFormatException</code> if none
*
* @exception NumberFormatException if the string value does not contain a
* parsable number.
* @see java.lang.Double#valueOf(java.lang.String)
*/
public double getDouble(String key) throws NumberFormatException;
/**
* Convenience API.
* Convert the value of the given key in this dialog settings
* to a float and return it.
*
* @param key the key
* @return the value coverted to float, or throws <code>NumberFormatException</code> if none
*
* @exception NumberFormatException if the string value does not contain a
* parsable number.
* @see java.lang.Float#valueOf(java.lang.String)
*/
public float getFloat(String key) throws NumberFormatException;
/**
* Convenience API.
* Convert the value of the given key in this dialog settings
* to a int and return it.
*
* @param key the key
* @return the value coverted to int, or throws <code>NumberFormatException</code> if none
*
* @exception NumberFormatException if the string value does not contain a
* parsable number.
* @see java.lang.Integer#valueOf(java.lang.String)
*/
public int getInt(String key) throws NumberFormatException;
/**
* Convenience API.
* Convert the value of the given key in this dialog settings
* to a long and return it.
*
* @param key the key
* @return the value coverted to long, or throws <code>NumberFormatException</code> if none
*
* @exception NumberFormatException if the string value does not contain a
* parsable number.
* @see java.lang.Long#valueOf(java.lang.String)
*/
public long getLong(String key) throws NumberFormatException;
/**
* Returns the IDialogSettings name.
*
* @return the name
*/
public String getName();
/**
* Returns the section with the given name in this dialog settings.
*
* @param key the key
* @return the section, or <code>null</code> if none
*/
public IPropertiesSettings getSection(String sectionName);
/**
* Returns all the sections in this dialog settings.
*
* @return the section, or <code>null</code> if none
*/
public IPropertiesSettings[] getSections();
/**
* Load a dialog settings from a stream and fill the receiver with its
* content.
*
* @param reader a Reader specifying the stream where the settings are read from.
*/
public void load(Reader reader) throws IOException;
/**
* Load a dialog settings from a file and fill the receiver with its
* content.
*
* @param fileName the name of the file the settings are read from.
*/
public void load(String fileName) throws IOException;
/**
* Adds the pair <code>key/value</code> to this dialog settings.
*
* @param key the key.
* @param value the value to be associated with the <code>key</code>
*/
public void put(String key,String[] value);
/**
* Convenience API.
* Converts the double <code>value</code> to a string and adds
* the pair <code>key/value</code> to this dialog settings.
*
* @param key the key.
* @param value the value to be associated with the <code>key</code>
*/
public void put(String key,double value);
/**
* Convenience API.
* Converts the float <code>value</code> to a string and adds
* the pair <code>key/value</code> to this dialog settings.
*
* @param key the key.
* @param value the value to be associated with the <code>key</code>
*/
public void put(String key,float value);
/**
* Convenience API.
* Converts the int <code>value</code> to a string and adds
* the pair <code>key/value</code> to this dialog settings.
*
* @param key the key.
* @param value the value to be associated with the <code>key</code>
*/
public void put(String key,int value);
/**
* Convenience API.
* Converts the long <code>value</code> to a string and adds
* the pair <code>key/value</code> to this dialog settings.
*
* @param key the key.
* @param value the value to be associated with the <code>key</code>
*/
public void put(String key,long value);
/**
* Adds the pair <code>key/value</code> to this dialog settings.
*
* @param key the key.
* @param value the value to be associated with the <code>key</code>
*/
public void put(String key,String value);
/**
* Convenience API.
* Converts the boolean <code>value</code> to a string and adds
* the pair <code>key/value</code> to this dialog settings.
*
* @param key the key.
* @param value the value to be associated with the <code>key</code>
*/
public void put(String key,boolean value);
/**
* Save a dialog settings to a stream
*
* @param writer a Writer specifying the stream the settings are written in.
*/
public void save(Writer writer) throws IOException;
/**
* Save a dialog settings to a file.
*
* @param fileName the name of the file the settings are written in.
*/
public void save(String fileName) throws IOException;
}/*
* $Log: IPropertiesSettings.java,v $
* Revision 1.2 2004/06/15 08:06:24 chenjp1
* Merge T20040615_BEFORE_MERGE (branch: reports)
*
* Revision 1.1.2.1 2004/03/03 02:23:52 chenjp1
* properties plus. powerful mechanism with primitive type array support.
*
*/
package com.coscon.util;import java.io.*;
import java.util.*;import javax.xml.parsers.*;import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Concrete implementation of a properties settings (<code>IPropertiesSettings</code>)
* using a hash table and XML. The properties store can be read
* from and saved to a stream. All keys and values must be strings or array of
* strings. Primitive types are converted to strings.
* <p>
* This class was not designed to be subclassed.
*
* Here is an example of using a PropertiesSettings:
* </p>
* <code>
* PropertiesSettings settings = new PropertiesSettings("root");
* settings.put("Boolean1",true);
* settings.put("Long1",100);
* settings.put("Array1",new String[]{"aaaa1","bbbb1","cccc1"});
* PropertiesSettings section = new PropertiesSettings("sectionName");
* settings.addSection(section);
* section.put("Int2",200);
* section.put("Float2",1.1);
* section.put("Array2",new String[]{"aaaa2","bbbb2","cccc2"});
* settings.save("c:\\temp\\test\\properties.xml");
* </code>
* Copied from <link>org.eclipse.jface.dialogs.DialogSettings</link>
* @author Chen Jipeng
* @version $Revision: 1.2 $ $Date: 2004/06/15 08:06:24 $
*/
public class PropertiesSettings implements IPropertiesSettings {
// The name of the PropertiesSettings.
private String name;
/* A Map of PropertiesSettings representing each sections in a PropertiesSettings.
It maps the PropertiesSettings' name to the PropertiesSettings */
private Map sections;
/* A Map with all the keys and values of this sections.
Either the keys an values are restricted to strings. */
private Map items;
// A Map with all the keys mapped to array of strings.
private Map arrayItems; private final String TAG_SECTION = "section";//$NON-NLS-1$
private final String TAG_NAME = "name";//$NON-NLS-1$
private final String TAG_KEY = "key";//$NON-NLS-1$
private final String TAG_VALUE = "value";//$NON-NLS-1$
private final String TAG_LIST = "list";//$NON-NLS-1$
private final String TAG_ITEM = "item";//$NON-NLS-1$
/**
* Create an empty dialog settings which loads and saves its
* content to a file.
* Use the methods <code>load(String)</code> and <code>store(String)</code>
* to load and store this dialog settings.
*
* @param sectionName the name of the section in the settings.
*/
public PropertiesSettings(String sectionName) {
name = sectionName;
items = new HashMap();
arrayItems = new HashMap();
sections = new HashMap();
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public IPropertiesSettings addNewSection(String name) {
PropertiesSettings section = new PropertiesSettings(name);
addSection(section);
return section;
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void addSection(IPropertiesSettings section) {
sections.put(section.getName(),section);
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public String get(String key) {
return (String)items.get(key);
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public String[] getArray(String key) {
return (String[])arrayItems.get(key);
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public boolean getBoolean(String key) {
return new Boolean((String)items.get(key)).booleanValue();
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public double getDouble(String key) throws NumberFormatException {
String setting = (String)items.get(key);
if(setting == null)
throw new NumberFormatException("There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$
return new Double(setting).doubleValue();
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public float getFloat(String key) throws NumberFormatException {
String setting = (String)items.get(key);
if(setting == null)
throw new NumberFormatException("There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$
return new Float(setting).floatValue();
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public int getInt(String key) throws NumberFormatException {
String setting = (String)items.get(key);
if(setting == null) {
//new Integer(null) will throw a NumberFormatException and meet our spec, but this message
//is clearer.
throw new NumberFormatException("There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$
}
return new Integer(setting).intValue();
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public long getLong(String key) throws NumberFormatException {
String setting = (String)items.get(key);
if(setting == null) {
//new Long(null) will throw a NumberFormatException and meet our spec, but this message
//is clearer.
throw new NumberFormatException("There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$
}
return new Long(setting).longValue();
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public String getName() {
return name;
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public IPropertiesSettings getSection(String sectionName) {
return (IPropertiesSettings)sections.get(sectionName);
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public IPropertiesSettings[] getSections() {
Collection values = sections.values();
PropertiesSettings[] result = new PropertiesSettings[values.size()];
values.toArray(result);
return result;
}
* Method declared on IPropertiesSettings.
*/
public void load(Reader r) {
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
// parser.setProcessNamespace(true);
document = parser.parse(new InputSource(r));
//Strip out any comments first
Node root = document.getFirstChild();
while(root.getNodeType() == Node.COMMENT_NODE){
document.removeChild(root);
root = document.getFirstChild();
}
load(document, (Element) root);
} catch (ParserConfigurationException e) {
} catch (IOException e) {
} catch (SAXException e) {
}
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void load(String fileName) throws IOException {
FileInputStream stream = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "utf-8"));//$NON-NLS-1$
load(reader);
reader.close();
}
/* (non-Javadoc)
* Load the setting from the <code>document</code>
*/
private void load(Document document,Element root) {
name = root.getAttribute(TAG_NAME);
NodeList l = root.getElementsByTagName(TAG_ITEM);
for (int i = 0; i < l.getLength(); i++){
Node n = l.item(i);
if(root == n.getParentNode()) {
String key = ((Element)l.item(i)).getAttribute(TAG_KEY);
String value = ((Element)l.item(i)).getAttribute(TAG_VALUE);
items.put(key,value);
}
}
l = root.getElementsByTagName(TAG_LIST);
for (int i = 0; i < l.getLength(); i++){
Node n = l.item(i);
if(root == n.getParentNode()) {
Element child = (Element)l.item(i);
String key = child.getAttribute(TAG_KEY);
NodeList list = child.getElementsByTagName(TAG_ITEM);
List valueList = new ArrayList();
for (int j = 0; j < list.getLength(); j++){
Element node = (Element)list.item(j);
if(child == node.getParentNode()) {
valueList.add(node.getAttribute(TAG_VALUE));
}
}
String[] value = new String[valueList.size()];
valueList.toArray(value);
arrayItems.put(key,value);
}
}
l = root.getElementsByTagName(TAG_SECTION);
for (int i = 0; i < l.getLength(); i++){
Node n = l.item(i);
if(root == n.getParentNode()) {
PropertiesSettings s = new PropertiesSettings("NoName");//$NON-NLS-1$
s.load(document,(Element)n);
addSection(s);
}
}
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void put(String key,String[] value) {
arrayItems.put(key,value);
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void put(String key,double value) {
put(key,String.valueOf(value));
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void put(String key,float value) {
put(key,String.valueOf(value));
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void put(String key,int value) {
put(key,String.valueOf(value));
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void put(String key,long value) {
put(key,String.valueOf(value));
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void put(String key,String value) {
items.put(key,value);
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void put(String key,boolean value) {
put(key,String.valueOf(value));
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void save(Writer writer) throws IOException {
Document document = new DocumentImpl();
save(document, (Node) document);
OutputFormat format = new OutputFormat();
format.setLineWidth(80);
format.setLineSeparator("\n");
format.setIndent(4);
format.setIndenting(true);
Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(writer, format);//$NON-NLS-1$
serializer.asDOMSerializer().serialize(document);
}
/* (non-Javadoc)
* Method declared on IPropertiesSettings.
*/
public void save(String fileName) throws IOException {
FileOutputStream stream = new FileOutputStream(fileName);
OutputStreamWriter writer = new OutputStreamWriter(stream, "utf-8");//$NON-NLS-1$
save(writer);
writer.close();
}
/* (non-Javadoc)
* Save the settings in the <code>document</code>.
*/
private void save(Document document,Node parent) {
Element root = document.createElement(TAG_SECTION);
parent.appendChild(root);
root.setAttribute(TAG_NAME, name);
for(Iterator i = items.keySet().iterator();i.hasNext();) {
String key = (String)i.next();
Element child = document.createElement(TAG_ITEM);
root.appendChild(child);
child.setAttribute(TAG_KEY, key);
child.setAttribute(TAG_VALUE, (String)items.get(key));
} for(Iterator i = arrayItems.keySet().iterator();i.hasNext();) {
String key = (String)i.next();
Element child = document.createElement(TAG_LIST);
root.appendChild(child);
child.setAttribute(TAG_KEY, key);
String[] value = (String[])arrayItems.get(key);
for (int index = 0; index < value.length; index++){
Element c = document.createElement(TAG_ITEM);
child.appendChild(c);
c.setAttribute(TAG_VALUE, value[index]);
}
}
for(Iterator i = sections.values().iterator();i.hasNext();) {
((PropertiesSettings)i.next()).save(document,root);
}
}
}/*
* $Log: PropertiesSettings.java,v $
* Revision 1.2 2004/06/15 08:06:24 chenjp1
* Merge T20040615_BEFORE_MERGE (branch: reports)
*
* Revision 1.1.2.2 2004/03/31 06:11:31 chenjp1
* change serialize element format
*
* Revision 1.1.2.1 2004/03/03 02:23:52 chenjp1
* properties plus. powerful mechanism with primitive type array support.
*
*/
* IniReader.java
* 用Java读取INI文件(带section的)
* 示例:
* tmp.IniReader reader = new tmp.IniReader("E:\\test.ini");
* out.println(reader.getValue("TestSect3", "kkk 6"));
*/ package tmp;import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties; public class IniReader { protected HashMap sections = new HashMap();
private transient String currentSecion;
private transient Properties current; public IniReader(String filename) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filename));
read(reader);
reader.close();
} protected void read(BufferedReader reader) throws IOException {
String line;
while ((line = reader.readLine()) != null) {
parseLine(line);
}
} protected void parseLine(String line) {
line = line.trim();
if (line.matches("\\[.*\\]")) {
currentSecion = line.replaceFirst("\\[(.*)\\]", "$1");
current = new Properties();
sections.put(currentSecion, current);
} else if (line.matches(".*=.*")) {
if (current != null) {
int i = line.indexOf('=');
String name = line.substring(0, i);
String value = line.substring(i + 1);
current.setProperty(name, value);
}
}
} public String getValue(String section, String name) {
Properties p = (Properties) sections.get(section); if (p == null) {
return null;
} String value = p.getProperty(name);
return value;
} }