Load the contents of the configuration file - Java java.io

Java examples for java.io:Properties

Description

Load the contents of the configuration file

Demo Code

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
  public static void main(String[] argv) {
    String configFile = "file://main.txt";
    System.out.println(loadConfigFile(configFile));
  }/*from   w  ww  .jav a  2s  . c  o  m*/

  /**************************************************************************
   * Load the contents of the configuration file
   **************************************************************************/
  static public java.util.Properties loadConfigFile(String configFile) {
    java.io.BufferedInputStream bin = null;
    java.io.InputStream in = openTextStream(configFile);
    java.util.Properties props = new java.util.Properties();

    if (in != null) {
      try {
        bin = new java.io.BufferedInputStream(in);
        props.load(bin);
        in.close();
      } catch (IOException ex) {
      }
    }
    return props;
  }

  /**************************************************************************
   * Open a URL or File as an InputStream
   **************************************************************************/
  static public InputStream openTextStream(String source) {
    java.io.InputStream in = null;
    java.net.URL url = null;

    // Try to open URL connection first
    try {
      try {
        url = new URL(source);
        in = url.openStream();
      } catch (MalformedURLException e) {
        // Try to open plain file, if `configFile' is not a
        // URL specification
        in = new FileInputStream(source);
      }
    } catch (java.io.IOException ex) {

    }
    return in;
  }
}

Related Tutorials