通過流檔案來進行properties檔案讀取的,要將檔案放入到assets檔案夾或者raw檔案夾中.例如,我們這裡有一個檔案test.properties,如果放入了assets檔案夾中,可以如下開啟:
Java代碼 www.2cto.com
Properties pro = new Properties();
InputStream is = context.getAssets().open("test.properties");
pro.load(is);
如果放入到raw檔案夾中,可以通過如下方式開啟:
Java代碼
InputStream is = context.getResources().openRawResource(R.raw.test);
Java代碼
Properties pro = new Properties();
pro.load(FileLoad.class.getResourceAsStream("/assets/test.properties"));
讀寫函數分別如下:
[java]
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public Properties loadConfig(Context context, String file) {
Properties properties = new Properties();
try {
FileInputStream s = new FileInputStream(file);
properties.load(s);
} catch (Exception e) {
e.printStackTrace();
}
return properties;
}
public void saveConfig(Context context, String file, Properties properties) {
try {
FileOutputStream s = new FileOutputStream(file, false);
properties.store(s, "");
} catch (Exception e){
e.printStackTrace();
}
}
orz,是不是發現什麼了?對了,這兩個函數與Android一點關係都沒有嘛。。
所以它們一樣可以在其他標準的java程式中被使用
在Android中,比起用純字串讀寫並自行解析,或是用xml來儲存配置,
Properties顯得更簡單和直觀,因為自行解析需要大量代碼,而xml的操作又遠不及Properties方便
使用方法如下:
寫入配置:
Properties prop = new Properties();
prop.put("prop1", "abc");
prop.put("prop2", 1);
prop.put("prop3", 3.14);
saveConfig(this, "/sdcard/config.dat", prop);
讀取配置:
Properties prop = loadConfig(this, "/sdcard/config.dat");
String prop1 = prop.get("prop1");
註:也可以用Context的openFileInput和openFileOutput方法來讀寫檔案
此時檔案將被儲存在 /data/data/package_name/files下,並交由系統統一管理
用此方法讀寫檔案時,不能為檔案指定具體路徑。
在android中,當我們打包產生apk後,將apk放入到真正的手機上時,你會找不到test.properties檔案,不要驚訝,android中的資源檔是只能存放在assets或者res的子目錄裡面的,程式包中的資源檔編譯後,是會丟失的!那麼是不是我們的第二種方法就沒法使用了?當然不是,經過實驗發現,將檔案放入到assets檔案夾裡,而在傳入路徑裡面填入檔案絕對路徑,還是可以引用該檔案的.