INI file format and Java encoding for read

Source: Internet
Author: User
Tags read ini file

INI is an abbreviation for initialization. INI file is a lightweight configuration file that is widely used in a variety of operating systems and software. INI file is a simple text file, the basic structure is simple, the readability is high, the necessary elements are only two: section, the property (including Name/key and value).
History:In MS-DOS and 16-bit Windows, until Windows Me, the INI file is used as the operating system profile (e.g. Win.ini, System.ini) to configure drivers, fonts, startup items, and so on. Various applications also widely use INI files to save their own configuration information.
After Windows NT, Microsoft began to adopt and promote the registry to save configuration information and to guide developers to use the registry as much as possible. However, since the registry is not available across operating systems, many applications like and continue to use INI files, even if some do not use INI as an extension (such as conf, TXT, etc.), but also using a similar section, the property of two elements.
Format/element:Property :The key (or name)/value is usually separated by the "=" number. A property occupies one row. Example:name = valuemyName = Zhang San
Section :is a number of property classification and grouping, a section occupies a row, the name is placed in brackets "[]" inside. All the property behind the section definition belongs to this section until the next section appears.
Case:In Windows, casing is not sensitive.
notes:Comments in windows are separated by a semicolon ";" The beginning of the text (Linux with the pound sign "#")
In addition to the standard definitions above, some applications support and supplement the format of other extensions: Blank Line: Some programs do not allow blank lines; Notes: Some programs support the use of the pound sign "#" as the beginning of comments, some programs do not allow comments and section, property mixed in a row; Duplicate name: If there is the name of the property, some procedures take the first, some take the last one, (the section of the same name does not matter, generally is to merge their properties); Escape Character: Some programs support escape characters, especially the backslash "\" as a two-line connector at the end of a row; Global Properties: Some programs support the ability to have properties before the first section tag and classify them as "global" sections; Space: Most programs support the processing of spaces before and after name/value, so that text alignment enhances readability; Order: The vast majority of programs are in the order of the section and property appearing;
comparison with other types of profiles:XML, JSON, YAML files: They all support nested definition properties, but they are heavy-weight configuration files, and the syntax is more complex.
Java Encoding implementation reads:The functions implemented:* Read INI files and store them in map
*
* Support with ' # ' or '; ' A comment at the beginning;
* Support line connector (the ' \ ' mark at the end of the line);
* Support the default global properties;
* Support list format (non-name=value format for list format);
* Support blank lines, name/value before and after the space;
* If there is a duplicate name, take the last one;
Code Details:
/** * Remove the comments in the INI file to ";"  or "#" at the beginning, the way to remove the BOM header of UTF-8 and other files * @param source * @return */private static string removeinicomments (string source) {string result = Source;if (Result.contains (";")) {result = result.substring (0, Result.indexof (";"));} if (Result.contains ("#")) {result = result.substring (0, Result.indexof ("#"));} Removal of UTF-8 bom!!! Using the editor in Windows to save the UTF-8 file, the first character in the file is this!!! if (Result.startswith ("\ufeff")) {//result = result.substring (1); result = Result.replace ("\ufeff", "");} return Result.trim ();} /** * Read INI file, store in map * * support to ' # ' or '; ' * Support line connector (the ' \ ' mark at the end of the line); * Support Default global properties; * Support list format (non-name=value format for list format); * Support blank lines, spaces before and after Name/value; * If there is a duplicate name, Take the last one; * * Format (example) as follows * * # I am a note *; I am also a note * * NAME0=VALUE0 # I am Global Properties * name10=value10 * * [normal section] # I'm a regular section * name1=value1 # I'm NA Me and value * * [list section] # I am only a section of value, with the first whether it contains ' = ' as the judging standard * value1 * value2 * * @param fileName * @return map< SectionName, Object> object is a map (storing name=value pairs) or list (storing only the value of the Properties) */public static map<string, object> readinifile (String fileName) {map<string, list<string>> Listresult = new hashmap<> (); map<string, object> result = new hashmap<> (); String globalsection = "global";        The KeyFile file = new file (fileName) of the global properties stored in the map;        BufferedReader reader = null;        try {reader = new BufferedReader (new FileReader (file));            reader = new BufferedReader (new InputStreamReader (new FileInputStream (file), "windows-1256"));            String str = NULL; String currentsection = globalsection;            Handle the default section list<string> currentproperties = new arraylist<> ();            Boolean linecontinued = false;                        String tempstr = null; Read one line at a time (non-empty) until read NULL is the end of the file//Put all first in listresult<string, list> while (str = Reader.readline ())!                   = null) {str = removeinicomments (str). Trim ();//Remove trailing notes, remove end and end spaces     if ("". Equals (str) | |            Str==null) {continue;            }//If the previous line includes the connector ' \ ' if (linecontinued = = true) {str = tempstr + str;            }//Processing line connector ' \ ' if (str.endswith ("\ \")) {linecontinued = true;            TempStr = str.substring (0,str.length ()-1);            Continue                        }else {linecontinued = false;} Whether a new section begins if (Str.startswith ("[") && Str.endswith ("]")) {String newsection = str.subs            Tring (1, Str.length ()-1). Trim (); If the new section is not in the present sections, then the current sections are stored in the Listresult if (!currentsection.equals (newsection)) {Listresult            . put (currentsection, currentproperties);                        Currentsection = newsection; Whether the new section duplicates the section//if it is, then use the original list to store the properties//if not, then a list to store properties Curre      Ntproperties=listresult.get (currentsection);      if (currentproperties==null) {currentproperties = new arraylist<> ();            }}}else{Currentproperties.add (str); }}//Save the last section in Listresult listresult.put (currentsection, Currentpropert                        IES);        Reader.close ();        } catch (IOException e) {e.printstacktrace ();                } finally {if (reader! = null) {try {reader.close (); } catch (IOException e1) {}}}//Defragment the Name=value pair and store it in map://From Lis Tresult<string, list>, see whether the element in the list contains an equal sign "=", if it is included, it is disassembled and placed in map//finishing, put the result into result<string, object> F                or (String Key:listResult.keySet ()) {list<string> templist = Listresult.get (key); The empty section is not placed inside the result if (templist==null| |        Templist.size () ==0) {continue;               } if (templist.get (0). Contains ("=")) {//name=value pair, stored in Map map<string, string> properties = new HASHMAP&LT;&G        t; ();        for (String s:templist) {int delimiterpos = S.indexof ("=");        Whitespace properties.put (s.substring (0,delimiterpos). Trim (), s.substring (Delimiterpos+1, S.length ()) before and after the equals sign. Trim ());        } result.put (key, properties);        }else{//Only value, gets the original list result.put (key, Listresult.get (key)); }} return result; @SuppressWarnings ("unchecked") public static void main (string[] args) {map<string, object> ini = readinifile ("d:/ Test.ini "); for (String K:ini.keyset ()) {System.out.println (k + ini.get (k));} System.out.println (((map<string, string>) ini.get ("MyInfo")). Get ("MyName"));

Test.ini File Contents:
I'm the # note # global SECTIONA=A_VALUEB = B_value[section1] #section1注释c =c_valuec1=c1_valued=d_value0&d_value1[list_ Section1]; section2 comment List1list2list3.1&list3.2&list3.3[section1] #重复的sectione = e_value=eeef=f_value[ MyInfo]myname= Lao Xu [list_section2]url1url2aldfjkjhlxmclk98u230jdslkmfsdlk2039840237509i09is0f980934285==234u093

Test results:
LIST_SECTION2[URL1, Url2aldfjkjhlxmclk98u230jdslkmfsdlk2039840237509i09is0f980934285==234u093]global{b=b_value, A=a_value}list_section1[list1, List2, List3.1&list3.2&list3.3]section1{f=f_value, d=d_value0&d_value1 , E=e_value=eee, C1=c1_value, c=c_value}myinfo{myname= old Xu} Lao Xu


Reference Document: Https://en.wikipedia.org/wiki/INI_file
(original article, reprint please specify the blog from Clement-xu)
comparison with other types of profiles:XML, JSON, YAML files: They all support nested definition properties, but they are heavy-weight configuration files, and the syntax is more complex.

Copyright NOTICE: This article is the original article, reprint please indicate the CSDN blog which is transferred from Clement-xu.

INI file format and Java encoding for read

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.