我想改進我的代碼,以便可以使用文本檔案連接到資料庫,但不能僅從文本檔案(我們設定登錄名、密碼、路徑、等那里)。
public class SQL {
public static Connection Connect() throws ClassNotFoundException, SQLException, IOException {
Properties props = new Properties();
FileInputStream in = new FileInputStream("E:/file.txt");
props.load(in);
in.close();
String driver = props.getProperty("jdbc.driver");
if (driver != null) {
Class.forName(driver);
}
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url, username, password);
}
問題出在這一行:
FileInputStream in = new FileInputStream("E:/file.txt")
如何FileInputStream使用txt檔案設定路徑?
到目前為止,我可以使用文本檔案設定登錄名、密碼和 URL,但我仍然有問題如何正確傳遞此文本檔案的地址(在文本檔案中)
uj5u.com熱心網友回復:
按照慣例,java 屬性檔案具有.properties擴展名。我建議您將檔案命名為jdbcconn.properties. 將該檔案放在與 file 相同的檔案夾中SQL.class。然后在您的 Java 代碼中,您可以執行以下操作。
Properties props = new Properties();
java.io.InputStream is = getClass().getResourceAsStream("jdbcconn.properties");
props.load(is);
參考類的javadocjava.lang.Class
請注意,在 Eclipse IDE 中,您將jdbcconn.properties檔案創建在與file 相同的檔案夾中SQL.java,當您構建專案時,Eclipse 會自動將檔案復制jdbcconn.properties到與 file 相同的檔案夾中SQL.class
uj5u.com熱心網友回復:
您正在尋找的是從external source. 幸運的足夠多,Java提供了一個API,可以幫助管理您的外部配置為keys/values與屬性檔案。
默認情況下,您的組態檔具有.properties擴展名,即config.properties. 如果您正在使用maven專案,您的組態檔將在此檔案夾中/src/main/resources。
然后,您將能夠按照上一個答案中提到的方式呼叫您的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343337.html
上一篇:唯一的絕對MySQL值
