Source for gnu.gcj.io.MimeTypes

   1: /* Copyright (C) 2000  Free Software Foundation
   2: 
   3:    This file is part of libgcj.
   4: 
   5: This software is copyrighted work licensed under the terms of the
   6: Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
   7: details.  */
   8: 
   9: package gnu.gcj.io;
  10: 
  11: import java.util.*;
  12: import java.io.*;
  13: 
  14: public class MimeTypes
  15: {
  16:   private static Hashtable mime_types;
  17:   
  18:   public static void fillFromFile (Hashtable table, String fname) 
  19:     throws IOException
  20:   {
  21:     LineNumberReader reader = 
  22:       new LineNumberReader (new FileReader (fname));
  23:     
  24:     while (reader.ready ())
  25:       {
  26:     StringTokenizer tokenizer = 
  27:       new StringTokenizer (reader.readLine ());
  28:     
  29:     try 
  30:       {
  31:         String t = tokenizer.nextToken ();
  32:         
  33:         if (! t.startsWith ("#"))
  34:           {
  35:         while (true)
  36:           {
  37:             // Read the next extension
  38:             String e = tokenizer.nextToken ();
  39:             if ((e != null) && (! e.startsWith ("#")))
  40:               table.put (e, t);
  41:             else
  42:               break;
  43:           }
  44:           }
  45:       } catch (NoSuchElementException ex) {
  46:         // Do nothing.
  47:       }
  48:       }
  49:   }
  50: 
  51:   // This is the primary interface to this class.
  52:   public static String getMimeTypeFromExtension (String extension)
  53:   {
  54:     if (mime_types == null)
  55:       {
  56:     mime_types = new Hashtable ();
  57:     
  58:     // First populate the hash table with the default mime type
  59:     // mappings.
  60:     int i = DefaultMimeTypes.types.length;
  61:     while (i > 1)
  62:       {
  63:         mime_types.put (DefaultMimeTypes.types[i - 2],
  64:                 DefaultMimeTypes.types[i - 1]);
  65:         i = i - 2;
  66:       }
  67:     
  68:     // Now read mime types from /etc/mime.types if it exists.
  69:     // This should override the default values.
  70:     try {
  71:       fillFromFile (mime_types, "/etc/mime.types");
  72:     } catch (IOException ex) {
  73:       // Do nothing.
  74:     }
  75:     
  76:     // Now read mime types from ~/.mime.types.  
  77:     // FIXME: We can't currently parse this file.
  78:       }
  79: 
  80:     String type = (String) mime_types.get (extension);
  81:     if (type == null)
  82:       return ("application/octet-stream");
  83:     else
  84:       return (type);
  85:   }
  86: }