Java--IDEA中使用properties配置文件通過JDBCUtils進行MySQL數據連接(NullPointerException,NoClassDefFoundError..)

在學習通過使用properties配置文件通過JDBCUtils進行MySQL數據連接,經常會出現NullPointerException或者NoClassDefFoundError 等錯誤,令人非常頭疼,今天我就歸納了一些問題出現的原因,以及一些解決方案。

Properties load 方式有兩種方式

void load(InputStream inStream) 

void load(Reader reader)

 

工程目錄結構:

 

JDBCUtils

package main;

import java.io.*;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;

   static{

       try {
           Properties pro = new Properties();
           //方式1 Xxx.class.getClassLoader().getResource 注意此方法路徑中不能包含中文
           String path = JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath();
           System.out.println(path);
           pro.load(new FileReader(path));
           //方式2 Xxx.class.getClassLoader().getResourceAsStream
        /*   InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
           pro.load(in);*/
            //方式3 Xxx.class.getResource
          /* String path = JDBCUtils.class.getResource("jdbc.properties").getPath();
           pro.load(new FileReader(path));*/
           //方式4 Xxx.class.getResourceAsStream
         /*  InputStream in = JdbcSQL.class.getResourceAsStream("jdbc.properties");
           pro.load(in);*/
           //方式5 resources/jdbc.properties
//           pro.load(new FileInputStream("resources/jdbc.properties"));

           url = pro.getProperty("url");
           user = pro.getProperty("user");
           password = pro.getProperty("password");
           driver = pro.getProperty("driver");
           Class.forName(driver);

       } catch (IOException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
   }

   public static Connection getConnection() throws SQLException {
       return DriverManager.getConnection(url, user, password);
   }

    public static void close(ResultSet rs, Statement stmt, Connection conn){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

/*   public  static void close(Statement stmt, Connection conn){
       close(null, stmt, conn);
   }*/

   }
}

 

 

JdbcSQL.java

package main;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class JdbcSQL {
    public static void main(String[] args) {
        //此處爲了測試jdbc.properties路徑
        String path = JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath();
        System.out.println(path);
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input user name:");
        String user = sc.nextLine();
        System.out.println("Please input password:");
        String password = sc.nextLine();

        boolean flag = new JdbcSQL().login(user, password);
        if (flag){
            System.out.println("登陸成功");
        }else{
            System.out.println("用戶名或密碼錯誤,請重新輸入");
        }
    }

    public boolean login(String user, String password){
        if (user == null || password == null){
            return false;
        }
        String sql = "select * from user where username='"+user+"' and password='"+password+"' ";
        System.out.println(sql);
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.close(rs, stmt, conn);
        }
        return false;
    }
}

 

運行結果:

Exception in thread "main" java.lang.NullPointerException
	at main.JdbcSQL.main(JdbcSQL.java:12)

Process finished with exit code 1
 

產生out文件夾:

方式一:Xxx.class.getClassLoader().getResource

注意此方法路徑中不能包含中文!!!!!

JDBCUtils核心配置jdbc.properties代碼:

//方式1 Xxx.class.getClassLoader().getResource 
String path = JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath();
System.out.println(path);
pro.load(new FileReader(path));

在E:\Test\src\jdbc.properties創建文件

jdbc.properties

url=jdbc:mysql:///db1
user=root
password=root
driver=com.mysql.jdbc.Driver

 

運行結果:

/E:/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
/E:/Test/out/production/Test/jdbc.properties
登陸成功

Process finished with exit code 0

注意:

1.其實運行程序,程序會將E:\Test\src\jdbc.properties文件複製到E:\Test\out\production\Test\jdbc.properties,而實際起作用是E:\Test\out\production\Test\jdbc.properties文件,也可以直接在E:\Test\out\production\Test中創建jdbc.properties文件。

 

2.使用方式一,路徑中不能有中文

jdbc.properties文件絕對路徑爲E:\測試\Test\src\jdbc.properties

讀取的路徑爲/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties出現FileNotFoundException錯誤

/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties
java.io.FileNotFoundException: E:\%e6%b5%8b%e8%af%95\Test\out\production\Test\jdbc.properties (系統找不到指定的路徑。)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110)
	at java.base/java.io.FileReader.<init>(FileReader.java:60)
	at main.JDBCUtils.<clinit>(JDBCUtils.java:21)
	at main.JdbcSQL.login(JdbcSQL.java:38)
	at main.JdbcSQL.main(JdbcSQL.java:20)
java.sql.SQLException: The url cannot be null
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:660)
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
	at main.JDBCUtils.getConnection(JDBCUtils.java:49)
	at main.JdbcSQL.login(JdbcSQL.java:38)
	at main.JdbcSQL.main(JdbcSQL.java:20)
用戶名或密碼錯誤,請重新輸入

Process finished with exit code 0

 

方式二:Xxx.class.getClassLoader().getResourceAsStream

注意此方法路徑中可以包含中文!

JDBCUtils核心配置jdbc.properties代碼

//方式2 Xxx.class.getClassLoader().getResourceAsStream
InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
pro.load(in);

運行結果:

在E:\Test\src\jdbc.properties創建文件jdbc.properties

url=jdbc:mysql:///db1
user=root
password=root
driver=com.mysql.jdbc.Driver

 

運行結果:

/E:/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陸成功

Process finished with exit code 0

 

拓展:路徑中可以包含中文,jdbc.properties文件絕對路徑爲E:\測試\Test\src\jdbc.properties

運行結果:

/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陸成功

Process finished with exit code 0

 

 

方式三: Xxx.class.getResource

注意此方式路徑中不能包含中文!!!

JDBCUtils核心配置jdbc.properties代碼

 //方式3 Xxx.class.getResource
String path = JDBCUtils.class.getResource("jdbc.properties").getPath();
pro.load(new FileReader(path));

 

運行出錯:

/E:/Test/out/production/Test/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class main.JDBCUtils
	at main.JdbcSQL.login(JdbcSQL.java:45)
	at main.JdbcSQL.main(JdbcSQL.java:20)

Process finished with exit code 1

 

在E:\Test\src\main\jdbc.properties創建文件:

運行結果:

/E:/Test/out/production/Test/main/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陸成功

Process finished with exit code 0

 

拓展:

此方法中路徑不能包含中文!

jdbc.properties文件絕對路徑爲E:\測試\Test\src\jdbc.properties

讀取的路徑爲/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/jdbc.properties出現FileNotFoundException錯誤

/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/main/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
java.io.FileNotFoundException: E:\%e6%b5%8b%e8%af%95\Test\out\production\Test\main\jdbc.properties (系統找不到指定的路徑。)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110)
	at java.base/java.io.FileReader.<init>(FileReader.java:60)
	at main.JDBCUtils.<clinit>(JDBCUtils.java:28)
	at main.JdbcSQL.login(JdbcSQL.java:38)
	at main.JdbcSQL.main(JdbcSQL.java:20)
java.sql.SQLException: The url cannot be null
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:660)
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
	at main.JDBCUtils.getConnection(JDBCUtils.java:49)
	at main.JdbcSQL.login(JdbcSQL.java:38)
	at main.JdbcSQL.main(JdbcSQL.java:20)
用戶名或密碼錯誤,請重新輸入

Process finished with exit code 0

 

方式四:Xxx.class.getResourceAsStream

注意此方法路徑中可以包含中文!!

JDBCUtils核心配置jdbc.properties代碼

//方式4 Xxx.class.getResourceAsStream
InputStream in = JdbcSQL.class.getResourceAsStream("jdbc.properties");
pro.load(in);

運行結果:

/E:/Test/out/production/Test/main/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陸成功

Process finished with exit code 0

 

拓展:

驗證路徑中可以包含中文

/E:/%e6%b5%8b%e8%af%95/Test/out/production/Test/main/jdbc.properties
Please input user name:
root
Please input password:
root
select * from user where username='root' and password='root' 
登陸成功

Process finished with exit code 0

 

 

方式五:resources/jdbc.properties

JDBCUtils核心配置jdbc.properties代碼

//方式5 resources/jdbc.properties
pro.load(new FileInputStream("resources/jdbc.properties"));

 

此方法需要在工程目錄結構中創建resources文件夾並設置爲Resources Root ,並在resources/jdbc.properties創建文件

 

總結規律:

1.Xxx.class.getClassLoader().getResource ,Xxx.class.getClassLoader().getResourceAsStream需要將xxx.properties文件放在工程的src文件夾下,如以上實驗放置在E:\Test\src文件夾下;

2.Xxx.class.getResource, Xxx.class.getResourceAsStream要將xxx.properties文件放在工程中Xxx.class文件的同一目錄下,如以上實驗放置在E:\Test\src\main文件夾下;

3.Xxx.class.getClassLoader().getResource , Xxx.class.getResource 方式中xxx.properties文件的路徑不能包含中文,不然會報NoClassDefFoundError 錯誤。

 

4.Xxx.class.getClassLoader().getResourceAsStream,Xxx.class.getResourceAsStream方式中xxx.properties文件的路徑可以包含中文。

 

5.resources/jdbc.properties方式需要創建resources文件夾並設置爲Resources Root ,並在resources/jdbc.properties創建文件。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章