java读取properties配置文件方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q601115211/article/details/81333462

在使用this.getClass().getResource(“/”).getPath() 在编辑器中能正常使用,但打成jar包后不能找到配置文件。

String filePath  = this.getClass().getResource("/").getPath();

需要使用 getResourceAsStream 方法来直接获取InputStream对象,而不是通过文件路径获取。
获取完InputStream对象后再转换成BufferReader。

private static final String PROPERTIES_NAME = "/conf/db.properties";

路径前要加 “/”
下面是完整代码

package mysql;
import java.io.*;
import java.sql.*;
import java.util.Properties;

public class TestMysqlConnection {

    private static final String PROPERTIES_NAME = "/conf/db.properties";
    public static String DB_URL = null;
    public static String DB_USER  = null;
    public static String DB_PWD   = null;



    public static Connection getConnection(){

        Properties properties = new Properties();
        try {
            InputStream ips = TestMysqlConnection.class.getResourceAsStream(PROPERTIES_NAME);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ips));

            properties.load(bufferedReader);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String driver;  //获取mysql数据库的驱动类
        driver = "com.mysql.jdbc.Driver";
        DB_URL = properties.getProperty("url");
        DB_USER = properties.getProperty("username");
        DB_PWD = properties.getProperty("password");
        System.out.println("driver:" +driver);
        System.out.println("url:" + DB_URL);
        System.out.println("name:" + DB_USER);
        System.out.println("pwd:" + DB_PWD);
        try{
            Class.forName(driver);
            Connection conn= DriverManager.getConnection(DB_URL,DB_USER,DB_PWD);//获取连接对象
            return conn;
        }catch(ClassNotFoundException e){
            e.printStackTrace();
            return null;
        }catch(SQLException e){
            e.printStackTrace();
            return null;
        }
    }
    public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){
        try{
            if(rs!=null){
                rs.close();
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
        try{
            if(ps!=null){
                ps.close();
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
        try{
            if(conn!=null){
                conn.close();
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws SQLException
    {
        Connection cc =TestMysqlConnection.getConnection();

        if(!cc.isClosed())
            System.out.println("Succeeded connecting to the Database!");
        else
            System.out.println("Error connecting to the Database!");
    }
}

猜你喜欢

转载自blog.csdn.net/q601115211/article/details/81333462