2010-05-07 23 views
2

我在我的blackberry項目(與Blackberry_App_Descriptor.xml文件位置相同)的根目錄下有一個config.properties文件,我嘗試訪問該文件以讀取和寫入該文件。 見下面我的課:Blackberry讀取項目中的本地屬性文件

public class Configuration { 
private String file; 
private String fileName; 

public Configuration(String pathToFile) { 
    this.fileName = pathToFile; 

    try { 
     // Try to load the file and read it 
     System.out.println("---------- Start to read the file"); 
     file = readFile(fileName); 
     System.out.println("---------- Property file:"); 
     System.out.println(file); 
    } catch (Exception e) { 
     System.out.println("---------- Error reading file"); 
     System.out.println(e.getMessage()); 
    } 
} 

/** 
* Read a file and return it in a String 
* @param fName 
* @return 
*/ 
private String readFile(String fName) { 
    String properties = null; 

    try { 
     System.out.println("---------- Opening the file"); 
     //to actually retrieve the resource prefix the name of the file with a "/" 
     InputStream is = this.getClass().getResourceAsStream(fName); 

     //we now have an input stream. Create a reader and read out 
     //each character in the stream. 
     System.out.println("---------- Input stream"); 
     InputStreamReader isr = new InputStreamReader(is); 

     char c; 

     System.out.println("---------- Append string now"); 
     while ((c = (char)isr.read()) != -1) { 
      properties += c; 
     } 
    } catch (Exception e) { 

    } 

    return properties; 
} 

}

我打電話給我的類的構造函數是這樣的:

Configuration config = new Configuration("/config.properties"); 

所以在我的課,「文件」應該有配置的所有內容。屬性文件,並且fileName應具有此值「/config.properties」。

但是「名稱」爲空,因爲找不到文件... 我知道這是該文件的路徑應該是不同的,但我不知道我可以改變什麼......類是在包com.mycompany.blackberry.utils

謝謝!

回答

0

試着將文件放在與該類相同的包中?

+0

我不想把我的配置文件放在某個地方,它需要在未來的項目中輕鬆訪問。 – Dachmt 2010-05-07 23:23:11

+0

原因是路徑「/config.properties"-如果你試圖把它放在那裏找到文件嗎?如果沒有,那麼包裝/項目設置有問題?代碼看起來很好。我使用非常相似的東西來獲取EULA文本,它適用於我 – bryanallott 2010-05-08 06:18:30

1

我認爲你需要將config.properties文件放到一個源文件夾中,當你建立這個項目時,你可以創建一個「resources」文件夾作爲src文件夾,並將其中的配置文件放在裏面,你可以得到文件中的應用程序

0
Class clazz = Class.forName("Configuration"); 
InputStream is = addFile.getResourceAsStream(fName);