[英]Unable to read properties file in java
我有一個主要的Class
,它是TestDriver.java
,我在其中調用functions
例如讀取到 excel 文件等等,為此,我需要在 java 中給出一個 excel 文件路徑,所以我使用的是屬性文件而不是硬編碼,並使用它我正在調用我的函數。 為了讀取屬性文件,我已經給出了文件路徑,但我無法讀取屬性文件...
文件:TestDriver.java
public class TestDriver
{
public static void main(String args[]){
String filePath = "E:\\Project\\HRMSAutomation\\";
Globals gbl = new Globals(filePath);
// Functions.....
}
}
文件:Globals.java
public class Globals
{
static String filePath;
public Globals(String path) {
this.filePath = path;
}
static Properties prop = Genlib.readConfig(filePath+"config.properties");
//readConfig is a method which will read the properties file
public static final String LOGIN_URL = prop.getProperty("loginUrl");
}
文件:Config.properties
loginUrl = someurl....
testsRoot = tests
configFileDir = E:/Project/Automation/Data/ConfigData/
錯誤日志。
java.io.FileNotFoundException: nullconfig.properties (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at gtlib.Genlib.readConfig(Genlib.java:96)
at projlib.Globals.<clinit>(Globals.java:15)
at testDrivers.TestDriver.main(TestDriver.java:89)
我收到錯誤,因為獲取空值的 filePath 變量可能是Globals.java
文件中的一些錯誤
我是 Java, static
字段的初始化在構造函數之前運行。 所以,當它初始化時, filePath
仍然是null
。 將初始化放在構造函數中,如下所示:
public class Globals {
static String filePath;
public Globals(String path) {
this.filePath = path;
prop = Genlib.readConfig(filePath+"config.properties"); //readConfig is a method which will read the properties file
}
static Properties prop;
public static final String LOGIN_URL = prop.getProperty("loginUrl");
}
另外,如果這是一個static
類,我建議您使用static
方法來初始化它而不是構造函數。
猜猜您使用的是純 Java 編碼風格。
通過以下代碼,您可以加載屬性並檢索某些參數
Properties prop = new Properties();
Class clazz = Object.class;
InputStream stream = clazz.getResourceAsStream({path}/Config.properties"); prop.load(stream);
filePath = prop.getProperty("configFileDir");
如果您使用 SpringBoot,工作會變得容易得多
config.properties
文件是確切名稱還是Config.properties
?
在Globals.java
你指的是: filePath+"config.properties"
我不確定 Genlib 但下面是加載屬性文件的簡單方法。 您必須提供的路徑是文件的相對路徑。 例如,文件可能位於
源代碼/測試/資源
所以你只需要像下面那樣做:
FileInputStream configFile = new FileInputStream("src/test/resources" + File.separator + "config.properties");
Properties configProperties = new Properties();
configProperties.load(configFile);
您的文件路徑是在類的構造函數中設置的,但您的屬性對象使用的是靜態類變量,該變量在創建該變量時進行初始化。
所以這意味着當你的屬性對象被初始化時,文件路徑還沒有設置,所以屬性試圖打開“nullconfig.properties”的文件名。
為什么將它們存儲為靜態? 如果它們不是靜態變量,您可以將它們全部移動到類變量中,並讓構造函數打開屬性文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.