[英]Assigning a destination for properties file in a java program
抱歉,如果這似乎是一個新手問題,並且確定它只是我需要更改的一小件事,但似乎我的程序無法找到我編寫的屬性文件的目標。
這是我的代碼
public String metrics() throws IOException {
String result = "";
Properties prop = new Properties();
String propFileName = "C:\\Users\\JChoi\\Desktop\\config.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(inputStream);
if (inputStream == null) {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String Metrics = prop.getProperty("Metrics");
result = Metrics;
System.out.println(result);
return result;
}
每當我運行代碼時,我都會收到一個nullpointerexception錯誤,但是,當我將屬性文件放入資源文件夾並將字符串名稱編輯為...
String propFileName = "config.properties";
工作正常...有什么建議嗎? 編輯:
String result = "";
Properties prop = new Properties();
String propFileName = "C:\\Users\\JChoi\\Desktop\\config.properties";
FileInputStream fileInputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(fileInputStream);
解決了!
String propFileName = "C:\\Users\\JChoi\\Desktop\\googlebatchfile\\config.properties";
BufferedInputStream inputStream;
FileInputStream fileInputStream = new FileInputStream(propFileName);
inputStream = new BufferedInputStream(fileInputStream);
您正在嘗試使用基於類路徑的輸入流來加載文件,但指定了文件路徑。
這個:
getClass().getClassLoader().getResourceAsStream(propFileName);
將嘗試從根開始搜索類路徑(基於類加載器認為根的任何內容)。
如果要從類路徑之外加載文件,則可能只想使用FileInputStream之類的東西。
如果您知道文件的完整路徑,請不要嘗試使用類路徑搜索打開它(這是getResourceAsStream()的作用)。
而是使用帶有路徑的inputsteam打開文件。 這是一些代碼:
FileInputStream inputStream = new FileInputStream(propFileName);
以下可能是更好的技術(我不確定屬性加載):
BufferedInputStream inputStream;
FileInputStream fileInputStream = new FileInputStream(propFileName);
inputStream = new BufferedInputStream(fileInputStream);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.