How to read the DB. properties file using Java

Source: Internet
Author: User

When reading the properties file, there were more or less strange issues. Here we will describe the final method of success.

Proputil tool class

public class PropUtil {private String filePath = null;public PropUtil(String fileName) {this.filePath = getClass().getClassLoader().getResource("/").getPath();filePath = filePath.substring(1, filePath.length() - 8) + fileName;// fixed tomcat readpath problem dml@2012.9.12filePath = filePath.replaceAll("%20", " ");}public Properties getProp() {Properties prop = new Properties();try {InputStream in = new BufferedInputStream(new FileInputStream(filePath));prop.load(in);in.close();} catch (Exception err) {err.printStackTrace();}return prop;}}

This tool class object can be directly instantiated during the call.

public static Connection getConnect() {PropUtil pu = new PropUtil("DB.properties");Properties p = pu.getProp();Connection con = null;try {String url = p.getProperty("url");String Driver = p.getProperty("driver");String user = p.getProperty("userName");String pwd = p.getProperty("password");Class.forName(Driver);con = DriverManager.getConnection(url, user, pwd);if (con == null) {System.out.println("can not find con");}} catch (Exception e) {System.out.println("conn bad!");e.printStackTrace();}return con;}

The above is the final configuration method in Tomcat.

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.