https://stackoverflow.com/a/9172615/2653579
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String ipAddress = settings.getString("IPAddress", "");
int port = settings.getInt("port", 0);
int title = settings.getString("Title", "");
}
我发现从配置文件读取值的代码,我不能让它从SD卡读取文件。我试过这种方式:
static File GPSCfgFile = new File(Environment.getExternalStorageDirectory()
+ "/Config/GPSLogService.cfg");
public static final String PREFS_NAME = String.valueOf(GPSCfgFile);
当我开始服务时,它会意外停止。这是在logcat:
FATAL EXCEPTION: main
GPSLogService.cfg.xml contains a path separator
如何让它从SD卡读取该文件?
答案 0 :(得分:0)
您可以使用String.valueOf()
方法获取文件:
如果您使用的是XML配置文件,可以查看此链接以了解如何执行此操作:
http://developer.android.com/training/basics/network-ops/xml.html#instantiate
http://www.vogella.com/articles/AndroidXML/article.html
如果您使用的是纯文本文件,可以在这里查看:
How can I read a text file from the SD card in Android?
在阅读配置文件时,您必须将每个值保存在单个SharedPreferences
:
SharedPreferences prefs = getSharedPreferences(ConstantsUtils.PREFERENCES,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("IPAddress", "Tag value" );
editor.commit();