1   /**
2    * Yksinkertainen luokka ini-tiedostojen lukemiseen.
3    * Rakennetaan sisäkkäisistä hajautustauluista koostuva rakenne.
4    *
5    * @author Markku Vire
6    * @version 1.0, 22.3.2003
7    */
8   
9   import java.io.*;
10  import java.util.Hashtable;
11  
12  public class Asetukset2
13  {
14    Hashtable lohkot = new Hashtable();
15  
16    public Asetukset2(String tiedosto) throws Exception
17    {
18      Hashtable avaimet = null;
19      String rivi;
20      BufferedReader r  = new BufferedReader(new FileReader(tiedosto));
21  
22      try {
23        while ((rivi = r.readLine()) != null)
24        {
25          rivi = rivi.trim();
26  
27          if (rivi.length() == 0 || rivi.charAt(0) == '#')
28            continue;
29  
30          if (rivi.charAt(0) == '[' && rivi.charAt(rivi.length() - 1) == ']')
31          {
32            // Uusi lohko havaittu => lisätään hajautustauluun.
33  
34            String lohkonNimi = rivi.substring(1, rivi.length() - 1).toLowerCase();
35  
36            avaimet = new Hashtable();
37            lohkot.put(lohkonNimi, avaimet);
38          }
39          else if (avaimet == null) {
40            throw new Exception("Avaimia lohkon ulkopuolella");
41          }
42          else {
43            int index = rivi.indexOf('=');
44  
45            String avain = rivi.substring(0, index).trim().toLowerCase();
46            String arvo  = rivi.substring(index + 1).trim();
47  
48            avaimet.put(avain, arvo);
49          }
50        }
51      }
52      finally {
53        try {
54          r.close();
55        } catch (IOException e) {
56        }
57      }
58    }
59  
60    public String hae(String lohko, String avain, String oletus)
61    {
62      Object o = lohkot.get(lohko.toLowerCase());
63  
64      if (o == null)
65        return oletus;
66  
67      Hashtable h = (Hashtable) o;
68  
69      o = h.get(avain.toLowerCase());
70  
71      if (o == null)
72        return oletus;
73  
74      return (String) o;
75    }
76  
77    public static void main(String[] args)
78    {
79      try {
80        Asetukset2 asetukset = new Asetukset2("tiedosto.ini");
81        String arvo = asetukset.hae("asetukset", "Toka", null);
82        System.out.println(arvo);
83      }
84      catch (Exception e) {
85        System.err.println(e);
86      }
87    }
88  }
89