写入特定行

时间:2017-09-18 20:44:14

标签: java android

如果以前曾询问过这个问题,请告诉我。

目标

在我的Android应用程序中,当用户启动App时,它首先加载Login.class。此类检查是否存在名为app_prefs.prop的本地文件(在应用程序的包含文件路径中)(它确实存在),然后检查以下字段,如下所示:

username=
user_hash=
saved_email=
email_hash=

默认情况下,这些字段是空白的。我正在使用以下代码阅读它们:

public static String getConfigValue(Context context, String name) {
    Resources resources = context.getResources();
    String TAG = "Retrieve";
    try {
        InputStream rawResource = resources.openRawResource(R.raw.app_prefs);
        Properties properties = new Properties();
        properties.load(rawResource);
        return properties.getProperty(name);
    } catch (Resources.NotFoundException e) {
        Log.e(TAG, "Unable to find the config file: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "Failed to open config file.");
    }
    return null;
}

如果他们返回空值,默认情况下会显示,则会显示登录屏幕。如果他们不这样做,默认情况下会尝试登录,如果成功则会继续登录App,如果没有,当然会再次显示登录。

问题

当他们登录时,我想将数据写入这些字段。目前,它使用JSON发送到服务器和从服务器发送,并且工作得很棒。我能够将这些数据提取到一个字符串变量中,然后在登录用户之后但在继续下一个App屏幕之前,我将其传递给我的保存到配置文件。这就是问题所在,我已经启用了许可

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我还将所有值传递给它,但它们也没有被写入我想要的行。这是我用来编写文件的代码:

private void commitUserInfotoFile(Context context, String username, String passhash, String rmemail, String rmemailhash) {
    Resources resources = context.getResources();
    String TAG = "Store";
    try {
        InputStream rawResource = resources.openRawResource(R.raw.app_prefs);
        Properties properties = new Properties();
        properties.load(rawResource);
        //tried using setProperty as well as put but neither works
        properties.setProperty("username", username);
        properties.put("username", username);
        properties.setProperty("user_hash", passhash);
        properties.setProperty("saved_email", rmemail);
        properties.setProperty("email_hash", rmemailhash);
        Log.e(TAG, "Wrote the values to the stored file");
    } catch (Resources.NotFoundException e) {
        Log.e(TAG, "Unable to find the config file: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IO Exception loading file.");
    }
}

然而,即使我在控制台中收到消息Wrote the values to the stored file,它也不会将这些值存储到文件中。我对使用这种方法编写属性感到有点困惑,所以任何帮助都会受到赞赏。感谢

1 个答案:

答案 0 :(得分:0)

您永远不会将编辑结果存储回资源中。 setProperty()只更新Properties对象中的一些内部键值对,它不会更新它的源。完成编辑后,需要调用Properties.store(OutputStream,String)。见这里:

https://developer.android.com/reference/java/util/Properties.html#store(java.io.OutputStream, java.lang.String)