简体   繁体   English

Android Studio写入.properties文件

[英]Android Studio write to .properties file

I followed Where to put own properties file in an android project created with Android Studio? 我关注了将自己的属性文件放在使用Android Studio创建的android项目中的位置? and I got an InputStream which reads from my .properties file successfully. 并且我得到了一个InputStream,它可以成功地从我的.properties文件读取。 However, I can't write to that .properties file, as there is no similar method to getBaseContext().getAssets().open ("app.properties") which returns an OutputStream. 但是,我无法写入该.properties文件,因为没有类似于getBaseContext()。getAssets()。open(“ app.properties”)的方法 ,该方法返回OutputStream。 I have also read Java Properties File appending new values but this didn't seem to help me, my guess is my file name for the file writer is wrong but I also tried "assets\\userInfo.properties" which also doesn't work. 我还阅读了附加新值的Java属性文件,但这似乎对我没有帮助,我猜是我的文件编写器文件名错误,但我也尝试了“ assets \\ userInfo.properties” ,但该方法也不起作用。

My .properties file is in src\\main\\assets\\userInfo.properties 我的.properties文件位于src \\ main \\ assets \\ userInfo.properties中

    Properties props = new Properties();
    InputStream inputStream = null;
    try{
        inputStream = getBaseContext().getAssets().open("userInfo.properties");
        props.load(inputStream);

        props.put("name", "smith");
        FileOutputStream output = new FileOutputStream("userInfo.properties"); //this line throws error
        props.store(output, "This is overwrite file");

        String name = props.getProperty("name");
        Log.d(TAG, "onCreate: PROPERTIES TEST NAME CHANGE: " + name);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Current code throws this error: 当前代码抛出此错误:

java.io.FileNotFoundException: userInfo.properties (Read-only file system) java.io.FileNotFoundException:userInfo.properties(只读文件系统)

You can't write to the assets folder, as it is inside the APK which is read-only. 您无法写入资产文件夹,因为它位于只读的APK内部。

Use internal or external storage instead 改用内部或外部存储

You can't write to the assets folder. 您无法写入资产文件夹。 If you want to update your properties file, you'll have to put them some place else. 如果要更新属性文件,则必须将它们放在其他位置。 If you want the initial version in the assets or raw folder, just copy it to the default files dir when the app is first used, then read from/write to it there. 如果您想要资产或原始文件夹中的初始版本,只需在首次使用该应用程序时将其复制到默认文件dir,然后在其中读取/写入即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM