使用Android中的文件操作写入和读取配置数据

时间:2012-02-07 07:41:16

标签: android file-io

在我的应用程序中有一些配置数据,例如ipaddress,portno,title等。我想私下将这些数据保存在手机中。我决定用以下格式写数据

IPAddress=127.0.0.1
Port=1234
Title=MyNewApplication

我对文件流感到困惑。我还想在不使用temperory文件的情况下更新值。请提供解决方案。

我尝试使用以下代码

public class Mtx {

public static final String PREFS_NAME = "MyPrefsFile";

public static void ConfWrite(String type, String value) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(null);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("IPAddress", "127.0.0.1");
    editor.putInt("port", 1234);
    editor.putString("Title", "MyNewApplication");

    // Commit the edits!
    editor.commit();
}

public static void ConfRead( String type, String value ) {

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(null);
        String ipAddress = settings.getString("IPAddress", "");
        int port = settings.getInt("port", 0);
        String title = settings.getString("Title", "");

        Log.e("", title);
}
}

1 个答案:

答案 0 :(得分:4)

请改用SharedPreferences。 简单易用。

详细信息可以在这里找到。

http://developer.android.com/guide/topics/data/data-storage.html

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

@Override
protected void onStop(){
   super.onStop();

  // We need an Editor object to make preference changes.
  // All objects are from android.context.Context
  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putString("IPAddress", "127.0.0.1");
  editor.putInt("port", 1234);
  editor.putString("Title", "MyNewApplication");

  // Commit the edits!
  editor.commit();
}}