第二篇: Ini 文件解析器

来源:互联网 发布:mac设置输入法切换 编辑:程序博客网 时间:2024/05/16 14:55

解析Windows的Ini文件。

  1. /*******************************************************************************
  2.  * QIniFile.java
  3.  *  
  4.  * Created: 2008-5-4 16:14:18 by @author GerryHua
  5.  *
  6.  * History:
  7.  *
  8.  *******************************************************************************/
  9. package jiamu.base.other;
  10. import java.io.BufferedReader;
  11. import java.io.BufferedWriter;
  12. import java.io.File;
  13. import java.io.FileInputStream;
  14. import java.io.FileNotFoundException;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import java.io.InputStreamReader;
  18. import java.io.OutputStreamWriter;
  19. import java.io.UnsupportedEncodingException;
  20. import java.util.Vector;
  21. import jiamu.base.exceptions.QException;
  22. import jiamu.base.functions.StringFunctions;
  23. import jiamu.base.functions.SystemFunctions;
  24. /**
  25.  * A class to handle the INI file.
  26.  */
  27. public class QIniFile {
  28.     /**
  29.      * A class to implement the section in INI file.
  30.      */
  31.     private class INISection {
  32.         /**
  33.          * The name of the section.
  34.          */
  35.         private String           name   = "";
  36.         /**
  37.          * The value collection of the section.
  38.          */
  39.         private Vector<INIValue> values = null;
  40.         /**
  41.          * Instantiate a new INI section.
  42.          * 
  43.          * @param name
  44.          *            the name of the section.
  45.          */
  46.         public INISection(String name) {
  47.             this.setName(name);
  48.             this.values = new Vector<INIValue>();
  49.         }
  50.         /**
  51.          * Add the value. Check the value first. If already exists, change the
  52.          * old value to the new value.
  53.          * 
  54.          * @param iniValue
  55.          *            the INIValue object.
  56.          * 
  57.          * @return the added INI value.
  58.          */
  59.         public INIValue addValue(INIValue iniValue) {
  60.             int pos = this.getValuePosition(iniValue);
  61.             if (pos == -1) {
  62.                 this.values.add(iniValue);
  63.                 return iniValue;
  64.             } else {
  65.                 this.values.get(pos).setValue(iniValue.getValue());
  66.                 return this.values.get(pos);
  67.             }
  68.         }
  69.         /**
  70.          * Add the INIValue with a line value.
  71.          * 
  72.          * @param lineValue
  73.          *            the line value.
  74.          */
  75.         public void addValue(String lineValue) {
  76.             this.values.add(new INIValue(lineValue));
  77.         }
  78.         /**
  79.          * Get the name of the section.
  80.          * 
  81.          * @return the name of the section.
  82.          */
  83.         public String getName() {
  84.             return this.name;
  85.         }
  86.         /**
  87.          * Get the value of special key.
  88.          * 
  89.          * @param key
  90.          *            the key.
  91.          * 
  92.          * @return the value.
  93.          */
  94.         public String getValue(String key) {
  95.             for (int i = 0; i < this.values.size(); i++) {
  96.                 if (key.compareToIgnoreCase(this.values.get(i).getName()) == 0) {
  97.                     return this.values.get(i).getValue();
  98.                 }
  99.             }
  100.             return null;
  101.         }
  102.         /**
  103.          * Get the position of the INIValue. Returns -1 if not found.
  104.          * 
  105.          * @param iniValue
  106.          *            the INIValue object.
  107.          * 
  108.          * @return the position in the value collection of the section. Returns
  109.          *         -1 if not found.
  110.          */
  111.         private int getValuePosition(INIValue iniValue) {
  112.             int pos = -1;
  113.             for (int i = 0; i < this.values.size(); i++) {
  114.                 if (iniValue.getName().compareToIgnoreCase(this.values.get(i).getName()) == 0) {
  115.                     pos = i;
  116.                     break;
  117.                 }
  118.             }
  119.             return pos;
  120.         }
  121.         /**
  122.          * Sets the name of the section.
  123.          * 
  124.          * @param name
  125.          *            the new name.
  126.          */
  127.         public void setName(String name) {
  128.             this.name = name;
  129.         }
  130.         /**
  131.          * Get the string of the object like
  132.          * <ul>
  133.          * <li>[Section]</li>
  134.          * <li>key1 = value1</li>
  135.          * <li>key2 = value2</li>
  136.          * </ul>
  137.          * 
  138.          * @return the string of the object .
  139.          */
  140.         @Override
  141.         public String toString() {
  142.             StringBuilder builder = new StringBuilder();
  143.             builder.append("[" + this.name + "]");
  144.             builder.append(SystemFunctions.getLineFeed());
  145.             for (int i = 0; i < this.values.size(); i++) {
  146.                 builder.append(this.values.get(i).toString());
  147.                 builder.append(SystemFunctions.getLineFeed());
  148.             }
  149.             builder.append(SystemFunctions.getLineFeed());
  150.             return builder.toString();
  151.         }
  152.     }
  153.     /**
  154.      * A class to implement the value in INI file.
  155.      */
  156.     private class INIValue {
  157.         /**
  158.          * The name of the INIValue.
  159.          */
  160.         private String name  = "";
  161.         /**
  162.          * The value of the INIValue.
  163.          */
  164.         private String value = "";
  165.         /**
  166.          * Instantiate a new INI value.
  167.          * 
  168.          * @param lineValue
  169.          *            the line value.
  170.          */
  171.         public INIValue(String lineValue) {
  172.             int pos = lineValue.indexOf('=');
  173.             this.name = lineValue.substring(0, pos).trim();
  174.             this.value = lineValue.substring(pos + 1).trim();
  175.         }
  176.         /**
  177.          * Get the name or the key of the INIValue.
  178.          * 
  179.          * @return the name or the key.
  180.          */
  181.         public String getName() {
  182.             return this.name;
  183.         }
  184.         /**
  185.          * Get the value of the INIValue.
  186.          * 
  187.          * @return the value.
  188.          */
  189.         public String getValue() {
  190.             return this.value;
  191.         }
  192.         /**
  193.          * Set the name of the INIValue.
  194.          * 
  195.          * @param name
  196.          *            the new name.
  197.          */
  198.         public void setName(String name) {
  199.             this.name = name;
  200.         }
  201.         /**
  202.          * Set the value of the INIValue.
  203.          * 
  204.          * @param value
  205.          *            the new value.
  206.          */
  207.         public void setValue(String value) {
  208.             this.value = value;
  209.         }
  210.         /**
  211.          * Get the string of the object like key = value
  212.          * 
  213.          * @return the string.
  214.          */
  215.         @Override
  216.         public String toString() {
  217.             return this.name + " = " + this.value;
  218.         }
  219.     }
  220.     /**
  221.      * Get the value of the key in the section in the INI file.
  222.      * 
  223.      * @param section
  224.      *            the section value.
  225.      * @param key
  226.      *            the key value.
  227.      * @param defaultValue
  228.      *            the default value.
  229.      * @param fileName
  230.      *            the INI file name.
  231.      * 
  232.      * @return the value.
  233.      * @throws QException
  234.      *             FileNotFoundException or IOException.
  235.      */
  236.     public static String getValue(String section, String key, String defaultValue, String fileName) throws QException {
  237.         QIniFile iniFile = new QIniFile(fileName);
  238.         iniFile.load();
  239.         String value = iniFile.getValue(section, key);
  240.         if (value == null) {
  241.             return defaultValue;
  242.         } else {
  243.             return value;
  244.         }
  245.     }
  246.     /**
  247.      * Sets the value of the key in the section in the INI file.
  248.      * 
  249.      * @param section
  250.      *            the section value.
  251.      * @param key
  252.      *            the key value.
  253.      * @param value
  254.      *            the value to be set.
  255.      * @param fileName
  256.      *            the ini file name.
  257.      * @throws QException
  258.      *             FileNotFoundException or IOException.
  259.      */
  260.     public static void setValue(String section, String key, String value, String fileName) throws QException {
  261.         QIniFile iniFile = new QIniFile(fileName);
  262.         iniFile.load();
  263.         iniFile.setValue(section, key, value);
  264.         iniFile.save();
  265.     }
  266.     /**
  267.      * The file name of the INI file.
  268.      */
  269.     private String             fileName = null;
  270.     /**
  271.      * The section collection in the INI file.
  272.      */
  273.     private Vector<INISection> sections = null;
  274.     /**
  275.      * Instantiate a new INI file.
  276.      * 
  277.      * @param fileName
  278.      *            the file Name.
  279.      * 
  280.      * @throws QException
  281.      *             FileNotFoundException or IOException.
  282.      */
  283.     public QIniFile(String fileName) throws QException {
  284.         this.fileName = fileName;
  285.         this.sections = new Vector<INISection>();
  286.         this.load();
  287.     }
  288.     /**
  289.      * Add the section. Check if the section exists. If not, add the new
  290.      * section.
  291.      * 
  292.      * @param section
  293.      *            the section.
  294.      * 
  295.      * @return the added INI section.
  296.      */
  297.     private INISection addSection(INISection section) {
  298.         int pos = this.getSectionPosition(section);
  299.         if (pos == -1) {
  300.             this.sections.add(section);
  301.             return section;
  302.         } else {
  303.             return this.sections.get(pos);
  304.         }
  305.     }
  306.     /**
  307.      * Create the file if the file doesn't exist.
  308.      * 
  309.      * @throws QException
  310.      *             the base exception.
  311.      */
  312.     private void createFile() throws QException {
  313.         File file = new File(this.fileName);
  314.         if (file.exists()) {
  315.             return;
  316.         }
  317.         try {
  318.             file.createNewFile();
  319.         } catch (IOException ex) {
  320.             throw new QException(ex, "QIniFile""createFile""");
  321.         }
  322.     }
  323.     /**
  324.      * Get the section position. If not found, return -1.
  325.      * 
  326.      * @param section
  327.      *            the section.
  328.      * 
  329.      * @return the position of the section. If not found, return -1.
  330.      */
  331.     private int getSectionPosition(INISection section) {
  332.         int pos = -1;
  333.         for (int i = 0; i < this.sections.size(); i++) {
  334.             if (section.getName().compareToIgnoreCase(this.sections.get(i).getName()) == 0) {
  335.                 pos = i;
  336.                 break;
  337.             }
  338.         }
  339.         return pos;
  340.     }
  341.     /**
  342.      * Get the string value of the key in the section.
  343.      * 
  344.      * @param sectionValue
  345.      *            the section value.
  346.      * @param keyValue
  347.      *            the key value.
  348.      * @param defaultValue
  349.      *            the default value.
  350.      * @param writeIfNotExists
  351.      *            indicates whether to write the value if not found.
  352.      * 
  353.      * @return the string value.
  354.      * 
  355.      * @throws QException
  356.      *             the base exception.
  357.      */
  358.     public String getString(String sectionValue, String keyValue, String defaultValue, boolean writeIfNotExists) throws QException {
  359.         String value = this.getValue(sectionValue, keyValue);
  360.         if (value == null) {
  361.             value = defaultValue;
  362.             if (writeIfNotExists) {
  363.                 this.setString(sectionValue, keyValue, value);
  364.             }
  365.         }
  366.         return value;
  367.     }
  368.     /**
  369.      * Get the value of the key in the section.
  370.      * 
  371.      * @param section
  372.      *            the section value.
  373.      * @param key
  374.      *            the key value.
  375.      * 
  376.      * @return the value.
  377.      */
  378.     public String getValue(String section, String key) {
  379.         for (int i = 0; i < this.sections.size(); i++) {
  380.             if (section.compareToIgnoreCase(this.sections.get(i).getName()) == 0) {
  381.                 return this.sections.get(i).getValue(key);
  382.             }
  383.         }
  384.         return null;
  385.     }
  386.     /**
  387.      * Load the INI file and create the structure.
  388.      * 
  389.      * @return true, if successful.
  390.      * 
  391.      * @throws QException
  392.      *             FileNotFoundException or IOException.
  393.      */
  394.     public boolean load() throws QException {
  395.         try {
  396.             this.createFile();
  397.             BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(this.fileName), "UTF-8"));
  398.             String lineValue = in.readLine();
  399.             INISection currentSection = null;
  400.             while (lineValue != null) {
  401.                 lineValue = lineValue.trim();
  402.                 if (!StringFunctions.isEmpty(lineValue)) {
  403.                     if (lineValue.startsWith("[")) {
  404.                         currentSection = new INISection(lineValue.substring(1, lineValue.length() - 1));
  405.                         this.addSection(currentSection);
  406.                     } else {
  407.                         if (currentSection != null) {
  408.                             currentSection.addValue(lineValue);
  409.                         }
  410.                     }
  411.                 }
  412.                 lineValue = in.readLine();
  413.             }
  414.             in.close();
  415.         } catch (FileNotFoundException ex) {
  416.             throw new QException(ex, "QIniFile""load""");
  417.         } catch (IOException ex) {
  418.             throw new QException(ex, "QIniFile""load""");
  419.         }
  420.         return true;
  421.     }
  422.     /**
  423.      * Save the file with the current structure.
  424.      * 
  425.      * @return true, if successful.
  426.      * 
  427.      * @throws QException
  428.      *             the IOException.
  429.      */
  430.     public boolean save() throws QException {
  431.         try {
  432.             BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.fileName), "UTF-8"));
  433.             out.append(this.toString());
  434.             out.close();
  435.         } catch (UnsupportedEncodingException ex) {
  436.             throw new QException(ex, "QIniFile""save""");
  437.         } catch (FileNotFoundException ex) {
  438.             throw new QException(ex, "QIniFile""save""");
  439.         } catch (IOException ex) {
  440.             throw new QException(ex, "QIniFile""save""");
  441.         }
  442.         return true;
  443.     }
  444.     /**
  445.      * Set the string value of the key in the section.
  446.      * 
  447.      * @param sectionValue
  448.      *            the section value.
  449.      * @param keyValue
  450.      *            the key value.
  451.      * @param setValue
  452.      *            the value to be set.
  453.      * 
  454.      * @throws QException
  455.      *             the base exception.
  456.      */
  457.     public void setString(String sectionValue, String keyValue, String setValue) throws QException {
  458.         this.setValue(sectionValue, keyValue, setValue);
  459.         this.save();
  460.     }
  461.     /**
  462.      * Set the value of the key in the section.
  463.      * 
  464.      * @param section
  465.      *            the section value.
  466.      * @param key
  467.      *            the key value.
  468.      * @param value
  469.      *            the value to be set.
  470.      */
  471.     public void setValue(String section, String key, String value) {
  472.         INISection iniSection = new INISection(section);
  473.         iniSection = this.addSection(iniSection);
  474.         iniSection.addValue(new INIValue(key + "=" + value));
  475.     }
  476.     /**
  477.      * Get the string of the object like the INI file content.
  478.      * 
  479.      * @return the string value.
  480.      */
  481.     @Override
  482.     public String toString() {
  483.         StringBuilder builder = new StringBuilder();
  484.         for (int i = 0; i < this.sections.size(); i++) {
  485.             builder.append(this.sections.get(i).toString());
  486.         }
  487.         return builder.toString();
  488.     }
  489. }

完。

PS:这次使用Opera,非常顺手。