java关于ini文件的生成与修改

java的一些工具包

http://www.oschina.net/project/tag/143/utils

在一些项目中经常用到保存一个配置文件,但是配置文件一般都用ini格式进行保存

那么对于该文件的类型怎么创建又怎么进行修改的呢?

下面是一种很方面的方法:

package cn.com.shine.ini;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Tools {

	static Map<String, Map<String, Object>> iniFile = new HashMap<String, Map<String, Object>>();


	public  void write(String name) throws IOException {
		StringBuilder sb = new StringBuilder("");
		for (String section : iniFile.keySet()) {
			sb.append("[").append(section).append("]").append("\n");
			Map<String, Object> map = iniFile.get(section);
			Set<String> keySet = map.keySet();
			for (String key : keySet) {
				sb.append(key).append("=").append(map.get(key)).append("\n");
			}
		}
		File file = new File(name);
		if (!file.exists()) {
			file.createNewFile();
		}
		try {
			OutputStream os = new FileOutputStream(file);
			os.write(sb.toString().getBytes());
			os.flush();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public  void setValue(String section, String key, Object value) {
		Map<String, Object> sectionMap = iniFile.get(section);
		if (sectionMap == null) {
			sectionMap = new HashMap<String, Object>();
			iniFile.put(section, sectionMap);
		}
		sectionMap.put(key, value);
	}

	public  Object getValue(String section, String key) {
		Object obj = null;
		Map<String, Object> item = iniFile.get(section);
		if (item != null) {
			obj = item.get(key);
		}
		return obj;

	}
}


方法调用:

package cn.com.shine.ini;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class IniSrc {
		/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Tools tools=new Tools();
		/*tools.setValue("ip", "ip_address", "183.126.125.152");
		tools.setValue("ip1", "ip_address1", "184.126.125.152");
		tools.setValue("ip2", "ip_address2", "185.126.125.152");
		tools.setValue("ip3", "ip_address3", "186.126.125.152");
		tools.setValue("ip4", "ip_address4", "187.126.125.152");*/
		tools.setValue("ip", "ip_address", "183");
		try {
			tools.write("E:\\NET.ini");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}


=======================================

另外一种是调用第三方jar包

http://javaini.sourceforge.net/

此类库可以在此下载:

不过不支持中文,若要需要支持中文,可以对源代码进行修改,如把编码格式修改就可以:

修改应该在这个地方:

/*
 * Java INI Package
 * Copyright (C) 2008 David Lewis
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public Licence for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

package org.dtools.ini;

import java.io.*;

/**
 * The IniFileWriter class is a simple class which allows the user to write an
 * IniFile object to the hard disk. One of the class' greatest advantage is that
 * it removes the complexity of writing files from the user.   
 * 
 * @author David Lewis
 * @version 0.3.0
 * @since 0.1.14
 */
public class IniFileWriter {

    /**
     * The text encoding for writing String to files.
     * @since 0.1.16
     */
	//把此编码格式变为UTF-8即可,就可以支持中文了。
    public static final String ENCODING = "ASCII";
    
    /**
     * The <code>IniFile<code> to write to the hard disk. 
     */
    private IniFile ini;
    
    /**
     * The file where to write the <code>IniFile</code> to
     */
    private File file;
    
    /**
     * Boolean value that, if true, adds a separate line before and after each
     * section.
     * 
     * @since 0.3.0
     */
    private boolean sectionLineSeparator;
    
    /**
     * Boolean value that, if true, adds a space character before and after the
     * equals character (<code>'='</code>) in an item.
     * 
     * @since 0.3.0
     */
    private boolean includeSpaces;
    
    /**
     * Boolean value that, if true, adds a separate line between each item.
     * 
     * @since 0.3.0
     */
    private boolean itemLineSeparator;

    /**
     * Creates a new IniFileWriter thread instance.
     * 
     * @param ini The IniFile to write.
     * @param file The File where to write the IniFile to.
     * 
     * @since 0.1.14
     */
    public IniFileWriter( IniFile ini, File file ) {

        if( ini == null ) {
            throw new IllegalArgumentException( "Cannot write a null IniFile" );
        }
        if( file == null ) {
            throw new IllegalArgumentException( 
                    "Cannot write an IniFile to a null file" );
        }
        
        this.ini = ini;
        this.file = file;
        
        // set parameters of IniFileWriter object
        setIncludeSpaces( false );
        setItemLineSeparator( false );
        setSectionLineSeparator( false );
    }
    
    /**
     * This method converts an INI file to a String object.
     * 
     * @param ini The IniFile to convert.
     * @return A String that represents the IniFile.
     * 
     * @since 0.1.14
     */
    private String iniToString( IniFile ini ) {
        
        // declare and initialise
        StringBuilder builder = new StringBuilder();

        //**********************************************************************
        // Loop through all the sections and append section to ini file
        //**********************************************************************
        
        int size = ini.getNumberOfSections();
        
        for( int i=0; i<size; i++ ) {
            IniSection section = ini.getSection(i);
            
            builder.append( sectionToString(section) );
            builder.append( IniUtilities.NEW_LINE );
        }
        
        // return text
        return builder.toString();
    }
    
    /**
     * <p>This method takes a pre or post comment from either an item or
     * section, and converts the comment to the correct format for a text file.
     * This is mainly for comments that are on multiple lines.</p>
     * 
     * @param comment The comment to format.
     * @param prefixNewLine If true, the new-line character is added before the
     *        comment (as in the case for post-comments). Otherwise, the
     *        new-line character is added after the comment (as in the case of
     *        pre-comments).
     * @return The comment in the correct format for a test file.
     * @since 0.3.0
     */
    private String formatComment( String comment, boolean prefixNewLine ) {
        
        StringBuilder sb = new StringBuilder();
        
        // if the comment is multiple lines, then split it and add each line
        // separately
        if( comment.contains( "\n" ) ) {
            
            String[] comments = comment.split( "\n" );
            
            for( String aComment : comments ) {
                
                if( prefixNewLine )
                    sb.append( IniUtilities.NEW_LINE );
                
                sb.append( Commentable.COMMENT_SYMBOL + aComment );
                
                if( !prefixNewLine )
                    sb.append( IniUtilities.NEW_LINE );
            }
        }
        else {
            if( prefixNewLine )
                sb.append( IniUtilities.NEW_LINE );
            
            sb.append( Commentable.COMMENT_SYMBOL + comment );
            
            if( !prefixNewLine )
                sb.append( IniUtilities.NEW_LINE );
        }
        
        return sb.toString();
    }
    
    /**
     * This method converts an IniItem to a String object.
     * 
     * @param item The IniItem to convert.
     * @return A String that best represents the IniItem
     * 
     * @since 0.1.14
     */
    private String itemToString(IniItem item) {

        //**********************************************************************
        // Declarations and initialisations
        //**********************************************************************
        String comment;
        StringBuilder builder = new StringBuilder();
        
        //**********************************************************************
        // if there is a pre-comment then add it
        //**********************************************************************
        comment = item.getPreComment();
        
        if( !comment.equals("") ) {
            builder.append( formatComment(comment,false) );
        }

        //**********************************************************************
        // add item
        //**********************************************************************
        if( includeSpaces ) {
            builder.append( item.getName() + " = " );
        }
        else {
            builder.append( item.getName() + "=" );
        }
        
        if( item.getValue() != null ) {
            builder.append( item.getValue() );
        }
        
        // if there is an end line comment, then add it
        if( !item.getEndLineComment().equals("") ) {
            builder.append( " " +
                    Commentable.COMMENT_SYMBOL + item.getEndLineComment() );
        }

        //**********************************************************************
        // if there is a post comment, then add it
        //**********************************************************************
        comment = item.getPostComment();

        if( !comment.equals("") ) {
            builder.append( formatComment(comment,true) );
            builder.append( IniUtilities.NEW_LINE );
        }
        else if( itemLineSeparator ) {
            builder.append( IniUtilities.NEW_LINE );
        }

        //**********************************************************************
        // return text
        //**********************************************************************
        return builder.toString();
    }
    
    /**
     * This method converts an IniSection object to a String object.
     * 
     * @param section The IniSection object to convert.
     * @return A String object that best represents the IniSection.
     * 
     * @since 0.1.14
     */
    private String sectionToString( IniSection section ) {

        //**********************************************************************
        // Declarations and initialisations
        //**********************************************************************
        String comment;
        StringBuilder builder = new StringBuilder();

        //**********************************************************************
        // check to see if sectionLineSeparator is set to true
        //**********************************************************************
        if( sectionLineSeparator ) {
            builder.append( IniUtilities.NEW_LINE );
        }
        
        //**********************************************************************
        // add pre-comment if one exists
        //**********************************************************************
        comment = section.getPreComment();
        
        if( !comment.equals("") ) {
            builder.append( formatComment(comment,false) );
        }

        //**********************************************************************
        // add section heading
        //**********************************************************************
        builder.append( "[" + section.getName() + "]" );

        //**********************************************************************
        // add end line comment
        //**********************************************************************
        comment = section.getEndLineComment();
        
        if( !comment.equals("") ) {
            builder.append( " " + Commentable.COMMENT_SYMBOL + comment );
        }

        //**********************************************************************
        // add post comment
        //**********************************************************************
        comment = section.getPostComment();

        if( !comment.equals("") ) {
            builder.append( formatComment(comment,true) );
            builder.append( IniUtilities.NEW_LINE );
        }
        else if( sectionLineSeparator ) {
            builder.append( IniUtilities.NEW_LINE );
        }
        
        //**********************************************************************
        // Loop through all the items and append section to ini file
        //**********************************************************************
        int size = section.getNumberOfItems();
        
        for( int i=0; i<size; i++ ) {
            IniItem item = section.getItem(i);
            builder.append( IniUtilities.NEW_LINE );
            builder.append( itemToString(item) );
        }

        //**********************************************************************
        // return text
        //**********************************************************************
        return builder.toString();
    }
    
    /**
     * This method sets whether a space character should be placed before and
     * after the equals character in an item.
     * 
     * @param value If true, a space character is placed before and after the
     *        equals character.
     *        
     * @since 0.3.0
     */
    public void setIncludeSpaces( boolean value ) {
        includeSpaces = value;
    }

    /**
     * This method sets whether an empty line should be included before and
     * after an item has occurred in the file.
     * 
     * @param value If true, an empty line will be included before and after an
     *        item.
     * @since 0.3.0
     */
    public void setItemLineSeparator( boolean value ) {
        itemLineSeparator = value;
    }
    
    /**
     * This method sets whether an empty line should be included before and
     * after a section has occurred in the file.
     * 
     * @param value If true, an empty line will be included before and after a
     *        section.
     * @since 0.3.0
     */
    public void setSectionLineSeparator( boolean value ) {
        sectionLineSeparator = value;
    }

    /**
     * <p>This method actually writes the <code>IniFile</code> to the File 
     * object (both of which are given in the constructor).</p> 
     * 
     * @throws IOException If an I\O exception occurs.
     * @since 0.1.14
     */
    public void write() throws IOException {
        BufferedWriter bufferWriter = null;
        
        // do not use FileWriter as you cannot manually set the character
        // encoding
        
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos, ENCODING );
        bufferWriter = new BufferedWriter( osw );
        
        bufferWriter.write( iniToString(ini) );
        bufferWriter.close();
    }
}

===================================================

例子:

//生成ini文件,并进行写入:

package cn.com.shine.ini;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import org.dtools.ini.BasicIniFile;
import org.dtools.ini.BasicIniSection;
import org.dtools.ini.IniFile;
import org.dtools.ini.IniFileReader;
import org.dtools.ini.IniFileWriter;
import org.dtools.ini.IniItem;
import org.dtools.ini.IniSection;

public class JavIni {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		IniFile iniFile=new BasicIniFile();
	
		
		IniSection dataSection=new BasicIniSection("123");
		
		iniFile.addSection(dataSection);
		
		IniItem nameIniItem=new IniItem("name");
		
		nameIniItem.setValue("利");
		dataSection.addItem(nameIniItem);
		
		IniItem ageIniItem=new IniItem("age");
		ageIniItem.setValue("23");
		dataSection.addItem(ageIniItem);
		
		
		IniSection dataSection2=new BasicIniSection("321");
		iniFile.addSection(dataSection2);
		
		IniItem nameIniItem2=new IniItem("name2");
		nameIniItem2.setValue("2");
		dataSection2.addItem(nameIniItem2);
		
		IniItem ageIniItem2=new IniItem("age2");
		ageIniItem2.setValue("232");
		dataSection2.addItem(ageIniItem2);
		
		
		File file=new File("F:\\TEST.ini");
		IniFileWriter niFileWriter=new IniFileWriter(iniFile, file);
		try {
			niFileWriter.write();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//IniFileReader niFileReader=new IniFileReader(iniFile, file);
	
		
	}

}

//读取文件,并进行修改

package cn.com.shine.ini;

import java.io.File;
import java.io.IOException;

import org.dtools.ini.BasicIniFile;
import org.dtools.ini.IniFile;
import org.dtools.ini.IniFileReader;
import org.dtools.ini.IniFileWriter;
import org.dtools.ini.IniItem;
import org.dtools.ini.IniSection;

public class Readf {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		IniFile iniFile=new BasicIniFile();
		File file=new File("F:\\TEST.ini");
		IniFileReader rad=new IniFileReader(iniFile, file);
		IniFileWriter wir=new IniFileWriter(iniFile, file);
		try {
			//读取
			rad.read();
			IniSection iniSection=iniFile.getSection(1);
			String string=iniSection.getName();
			IniItem iniItem=iniSection.getItem("age2");
			String name=iniItem.getValue();
			
			//修改
			iniItem.setValue("agaeaaaaaaaaaaaaaaaa");
			iniSection.addItem(iniItem);
			iniFile.addSection(iniSection);
			wir.write();
			
			System.out.println(string+"-212-"+name);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
http://download.csdn.net/detail/u010581811/6469605

源码下载:

http://download.csdn.net/detail/u010581811/6469605

你可能感兴趣的:(java,javaini)