配置的资源文件找不到路径
1.读取系统文件中的内容,代码如下:
import java.io.FileInputStream;
import java.util.Properties;
public class Read {
static Properties pro =new Properties();
static FileInputStream fis = null;
public String getPath() {
String path = getClass().getClassLoader().getResource( "my.properties ").getPath();
path = path.substring(1, path.length());
return path;
}
public static void open() throws Exception {
Read r = new Read();
String path = r.getPath();
fis = new FileInputStream(path);
pro.load(fis);
}
public static String getString(String name) throws Exception {
open();
String newname = pro.getProperty(name);
return newname;
}
public static void main(String[] args) throws Exception {
Read r = new Read();
String path = r.getPath();
System.out.println(path);
String url = r.getString( "url ");
System.out.println(url);
}
}
进行单体测试时可以读到url。
打印出的路径: C:/workspace/Test/WebRoot/WEB-INF/classes/my.properties
取得文件内容: jdbc:oracle:thin:@192.168.0.1:1521:test
--------------------------------
2.链接数据库,代码如下
import com.ReadProperties;
import
java.io.IOException;
import java.sql.*;
public class getCon {
private String url = null;
private String username = null;
private String password = null;
private String driver = null;
ReadProperties rp = new ReadProperties();
Connection con = null;
public Connection getConn() throws Exception {
driver = Read.getString( "driver ");
url = Read.getString( "url ");
username = Read.getString( "username ");
password = Read.getString( "password ");
try {
try {
Class.forName(driver).newInstance();
} catch (
InstantiationException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (
IllegalAccessException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (
ClassNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
con = DriverManager.getConnection(url, username, password);
} catch (
SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return con;
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {