當前位置:編程學習大全網 - 編程語言 - 如何在Android開發中對properties文件進行讀取

如何在Android開發中對properties文件進行讀取

通過流文件來進行properties文件讀取的,要將文件放入到assets文件夾或者raw文件夾中.例如,我們這裏有壹個文件test.properties,如果放入了assets文件夾中,可以如下打開:

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"));

讀寫函數分別如下:

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();

}

}

是不是發現什麽了?對了,這兩個函數與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文件夾裏,而在傳入路徑裏面填入文件絕對路徑,還是可以引用該文件的.

  • 上一篇:小馬智行直奔L4的底氣從何而來?
  • 下一篇:第六屆全國信息技術應用水平大賽 移動互聯網站設計(Dreamweaver)都有哪些內容?
  • copyright 2024編程學習大全網