Search code examples
androidconfigread-write

How to read a config file which is located at project path in Android?


In my application there are some configuration data, such as ipaddress, portno, title and etc. I want to keep these data in phone and out of the application in config.And I will read from and write to this file.How can I do that?If not what can you suggest me to do that?

IPAddress=127.0.0.1 Port=1234


Solution

  • Yes, you can read and write files, and in reading from a file, you can set a variable. I'll assume that you're capable of handling all of the gui related tasks involved with prompting users for input, as that is really a different question.

    My explanation is largely from the Android Developer Docs, where you can read more fully at this link Using External Files

    First, we'll assume that your user wants to load the settings file from the Downloads directory. You'll need permissions to use the external storage, add the following to your manifest, between the <manifest> tags:

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

    Before you try to access the file, you'll want to check the state of your system's external storage, to see if you can read from it

    String state = Environment.getExternalStorageState();
    boolean isReadable =  (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
    

    If the external storage is readable, you can get a hold of an external file, we're going to call it "settings" within the Downloads directory :

    private static final SETTINGS_FILENAME = "settings";
    ...
    public File getSettingsFile() {
        // Get the directory for the user's public downloads directory.
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), SETTINGS_FILENAME);
        if (!file.exists()) {
            Log.e(LOG_TAG, "The settings file does not exist");
        }
        return file;
    }
    

    Now, you have access to the File that you emailed to your client. You will use the standard interface, which I linked to, to read the file and internalize its settings.

    Again, this is all just sourced from the developer docs, with slight modification. I hope that that helps you.