seeRead and write values from INI files
http://www.codeguru.com/java/articles/655.shtml

解决方案 »

  1.   

    import java.io.*;
    import java.util.*;/**
     * Title:        读取指定配置文件的Bean
     * Description:  
     * 读取指定文件的内容,可以读一个指定的行或者整个文件。
     * 文件应是文本形文件如*.ini,*.txt等。文件的每一行格式应为:key=value,
     * 其中key是属性名,value是属性值。
     * Copyright:    Copyright (c) 2001
     * Company:      
     * @author      
     * @version 1.0
     */public class GetConfig {
     String hostfile=null;
     String hostip=null;          //普通IP。
     RandomAccessFile raf=null;  /**
       * 默认的构造函数
       */
      public GetConfig() {
       String hostfile=null;
       String hostip=null;          //普通IP。
       RandomAccessFile raf=null;
      }  /**
       * 设置要读取的文件的绝对路径包括路径和文件名。
       * <br>
       * @param s 是指定的文件全路径名。
       */
      public void setHostFileName(String s) {
        hostfile=s;
        }  /**
       * 读取文件中的指定行。
       * <br>
       * @param linetoread是要读的行的行数。第一行从1开始计数。
       * @return 返回指定行中key=value的value部分.
       */
      public String getConfigLine(int linetoread) {
        boolean reachtail=false;
       try {
        raf=new RandomAccessFile(hostfile,"r");
        if (raf==null) {
          System.out.println("找不到指定的文件:"+hostfile);
          System.exit(-1);
          }
        for(int currline=1;!reachtail & currline<=linetoread;currline++) {
         try {
           hostip=raf.readLine();
          }
         catch(Exception e) {
           System.out.println("已读到文件末尾或出现错误。");
                              }
            }   //end for    if(!reachtail & hostip!=null) {
    //     hostip=raf.readLine();
         hostip=hostip.substring((hostip.indexOf('=')==-1)?hostip.length():hostip.indexOf('=')+1);
             }
        else {
         System.out.println("在文件"+hostfile+"找不到指定读取的行,请检查指定行数的合适性。");
         hostip="在文件"+hostfile+"找不到指定读取的行,请检查指定行数的合适性。";
        }
         }
        catch (IOException e) {
         System.out.println("读写文件时错误:"+e.getMessage());
         }
        finally {
         try {  raf.close(); }
         catch(IOException e) {}
        }
        return hostip;
       }
      /**
       * 读取文件的所有行。
       * <br>
       * @return 返回一个Properties对象,此对象包含文件中的所有行的属性名和属性值。
       */
      public Properties getConfigFile() {
       Properties pr=new Properties();
        try {
         pr.load(new FileInputStream(hostfile));
         }
        catch(IOException e) {
         System.out.println("找不到指定文件:"+hostfile);
         return null;
         }
         return pr;
        }
    }
      

  2.   

    直接用properties或者xml来读配置文件