[英]<identifier> expected in Java
我正在嘗試從類中的屬性文件中加載數據。但是我收到<identifier> expected
錯誤<identifier> expected
。
public class ToDoList {
private Properties prop = new Properties();
{
prop.load(this.getClass().getClassLoader().getResourceAsStream("file.properties"));//Here i am getting the error
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
錯誤就像
<identifier> expected
illegal start of type
')' expected
';' expected
illegal start of type
<identifier> expected
';' expected
invalid method declaration; return type required
';' expected
您忘記了try
關鍵字。 它應該是
try {
// statements
} catch (IOException ioe) {
// handle exception
}
並且不要忘記將代碼放入方法中。
您使用了初始化程序塊{ ... }
但是它不能有catch塊,也不能嘗試。
在該級別,僅允許字段,構造函數,類和方法聲明。
我的解決方案全部放在構造函數中。
public ToDoList() {
try {
prop.load(this.getClass().getClassLoader().getResourceAsStream("file.properties"));
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
我認為您的屬性文件如下所示:
someName1=someValue1
someName2=someValue2
someName3=someValue3
在我的情況下,properties文件位於項目的根文件夾中。
但這不是必需的。
public class Application
{
public static void main(String[] args)
{
Properties prop = new Properties();
try
{
InputStream input = new FileInputStream("./test.properties");
prop.load(input);
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println(prop.get("someName1"));
System.out.println(prop.get("someName2"));
System.out.println(prop.get("someName3"));
}
}
這顯示了我在屬性文件中設置的值
請注意,您沒有在代碼中調用任何函數:
public class ToDoList {
//Here you declare your properties
private Properties prop = new Properties();
{// this is not a function
prop.load(this.getClass().getClassLoader().getResourceAsStream("file.properties"));//Here i am getting the error
}
catch (IOException ioe) // you dont start a try-clause
{
ioe.printStackTrace();
}
}
更改為:
public class ToDoList {
private Properties prop = new Properties();
public ToDoList(){ //Constructor of the class
try{
// declare the inputstream with that file
InputStream input = new FileInputStream("file.properties");
prop.load(input);
}
catch (IOException ioe)
{
// Error handling code here
ioe.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.