Java Read configuration file information

Source: Internet
Author: User

1. First, the engineering structure is as follows:

Note:
A. The two files in blue are labeled with the COM Kanehira level, both under SRC. Ennnotificationpushproxy.ini is the configuration file for this project, and Log4j.properties is the configuration file for log4j.
B. Two files marked in red, Configutil.java is used to read Ennnotificationpushproxy.ini, Logutil.java is read log4j.properties.

2. Configutil.java content:
Package com.ecity.enn.notification.proxy.util;

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import java.io.IOException;
Import java.util.Enumeration;
Import Java.util.HashMap;
Import java.util.Properties;

public class Configutil {
private static final String Ini_file_name = "/ennnotificationpushproxy.ini";
private static hashmap<string, string> propertymap = null;

static {
PropertyMap = new hashmap<string, string> ();
String path = Urlutil.getclasspath (configutil.class) + ini_file_name;
Logutil.debug ("Ennnotificationpushproxy.ini path=" + path);
File File = new file (path);

FileInputStream instream = null;
try {
instream = new FileInputStream (file);
} catch (FileNotFoundException e) {
Logutil.error (e);
}

Properties Properties = new properties ();
try {
Properties.load (instream);
} catch (IOException e) {
Logutil.error (e);
}

@SuppressWarnings ("Unchecked")
enumeration<string> keys = (enumeration<string>) properties.propertynames ();

while (Keys.hasmoreelements ()) {
String key = Keys.nextelement ();
Propertymap.put (Key.tolowercase (), Properties.getproperty (key));
}
}

public static string get (String key) {
Return Propertymap.get (Key.tolowercase ());
}

public static int getInt (String key) {
String valuestr = Propertymap.get (Key.tolowercase ());
int value = 0;
try {
Value = integer.valueof (VALUESTR);
} catch (Exception e) {
Logutil.error (e);
Value = 0;
}

return value;
}

public static long Getlong (String key) {
String valuestr = Propertymap.get (Key.tolowercase ());
Long value = 0;
try {
Value = long.valueof (VALUESTR);
} catch (Exception e) {
Logutil.error (e);
Value = 0;
}

return value;
}

public static void Set (string key, String value) {
if (get (key) = = null) {
Propertymap.put (key, value);
}
}
}

3. Logutil.java content:
Package com.ecity.enn.notification.proxy.util;

Import Org.apache.log4j.Logger;
Import Org.apache.log4j.PropertyConfigurator;

public class Logutil {
private static final Logger Logger;
private static final String Ini_file_name = "/log4j.properties";
private static final String TAG = "Ennnotificationpushproxy";

static {
System.out.println ("projecthomepath=" + Urlutil.getprojecthomepath ());
System.setproperty ("Workdir", Urlutil.getprojecthomepath ());
String path = Urlutil.getclasspath (logutil.class) + ini_file_name;
Propertyconfigurator.configure (path);
Logger = Logger.getlogger (TAG);
}

public static void Debug (Object message) {
Logger.info (message);
}

public static void Debug (String message, Throwable e) {
Logger.info (message, E);
}

public static void info (String message) {
Logger.info (message);
}

public static void info (String message, Throwable e) {
Logger.info (message, E);
}

public static void error (String message) {
Logger.error (message);
}

public static void error (Object message, Throwable e) {
Logger.error (message, E);
}

public static void error (Throwable e) {
Logger.error ("", e);
}
}
Note: Note the setting of the value of Workdir. Its value is the location of the current project.

4. Log4j.properties content:
log4j.rootlogger=all, serverdailyrollingfile, stdout  
log4j.appender.serverdailyrollingfile=org.apache.log4j.dailyrollingfileappender  
Log4j.appender.serverdailyrollingfile.datepattern= '. ' yyyy-mm-dd  
log4j.appender.serverdailyrollingfile.file=${workdir}/logs/ ennnotificationpushproxy.log  
log4j.appender.serverdailyrollingfile.layout= org.apache.log4j.patternlayout  
log4j.appender.serverdailyrollingfile.layout.conversionpattern=% d{yyyy-mm-dd hh:mm:ss} %p [%c] %m%n  
log4j.appender.serverdailyrollingfile.append=true  
  
log4j.appender.stdout= org.apache.log4j.consoleappender  
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout   
Log4j.appender.stdout.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:ss} %p [%c]  %m%n  
Note: Note the use of the Workdir variable. Under this configuration, the logs file is generated in the root directory of the project.

5. In Configutil.java and Logutil.java, urlutil classes are used. As follows:
Package com.ecity.enn.notification.proxy.util;

Import Java.io.File;
Import java.io.UnsupportedEncodingException;
Import Java.net.URL;

/**
* <p>
* Title:url Auxiliary Tool class
* </p>
*/
public class Urlutil {
/**
*
* Description: Gets the file where the current class resides
*/
public static File Getclassfile (class<?> clazz) {
URL path = Clazz.getresource (Clazz.getname (). substring (Clazz.getname (). LastIndexOf (".") + 1) + ". Class");
if (path = = null) {
String name = Clazz.getname (). ReplaceAll ("[.]", "/");
Path = Clazz.getresource ("/" + Name + ". Class");
}
return new File (Path.getfile ());
}

/**
* Description: Solve Chinese coding problem with Getclassfile
*/
public static String Getclassfilepath (class<?> clazz) {
try {
Return Java.net.URLDecoder.decode (Getclassfile (clazz) GetAbsolutePath (), "UTF-8");
} catch (Unsupportedencodingexception e) {
E.printstacktrace ();
Return "";
}
}

/**
*
* Description: Gets the classpath directory where the current class resides
*
* @param clazz
* @return
* @mail [email protected]
* @since: Sep, 12:32:27 PM
*/
public static File Getclasspathfile (class<?> clazz) {
File File = Getclassfile (clazz);
for (int i = 0, count = Clazz.getname (). Split ("[.]"). Length I < count; i++)
File = File.getparentfile ();
if (File.getname (). toUpperCase (). EndsWith (". jar! ")) {
File = File.getparentfile ();
}
return file;
}

/**
*
* Description: Solve Chinese coding problem with Getclasspathfile
*
* @param clazz
* @return
* @mail [email protected]
* @since: Sep, 1:10:37 PM
*/
public static String Getclasspath (class<?> clazz) {
try {
Return Java.net.URLDecoder.decode (Getclasspathfile (clazz) GetAbsolutePath (), "UTF-8");
} catch (Unsupportedencodingexception e) {
E.printstacktrace ();
Return "";
}
}

public static String Getprojecthomepath () {
String path = Getclasspath (Urlutil.class);
String Webapppath = path.substring (0, Path.touppercase (). LastIndexOf ("Web-inf")). ReplaceAll ("%20", "");

return webapppath;
}

public static void Main (string[] args) throws Unsupportedencodingexception {
System.out.println (Getclassfilepath (Urlutil.class));
System.out.println (Getclasspath (Urlutil.class));
}
}

6. Final deployment results:
A. The location of the two configuration files is under classes. As follows:

B. The logs folder is under the project root directory. The log file is under the Logs folder. As follows:

Java Read configuration file information

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.