[SOLVED] Read / Write file on Android

I am just needing to save/read an string on an file, how to correctly do this on Android ?
I know you need special permission to do this on SD card, but on about the internal card ?
There is any easy way to do this ? Do I need to setup permissions, keys etc ?

You need to add this

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

this make things easier to manage and writing externally saves you many headaches even if the device has no SD card inside. and this permission is only for sdk 18 and bellow, hence the maxSdkVersion attribute

This is the setup that worked for me:

To look for the text file we will use regularly:

private File getAndroidFile(){
         File folder = JmeSystem.getStorageFolder();
        if(folder != null && folder.exists()){
            File file = new File(folder, "saveFile.txt");
            if(!file.exists()){
                try {
                    file.createNewFile();
                    //Set default data is you want
                } catch (IOException ex) {
                    //catch error here
                }
                return file;
            }else{
                return file;
            }
        }
        return null;
    }

To write to that file I just use FileWriter

private boolean saveData(){       
        File file = getAndroidFile();
        if(null == file){
            return false;
        }
        boolean saved = false;
        try {
            FileWriter writer = new FileWriter(file, false);
            writer.write("MyKey1=" + getValue() + "\r\n"); //Saving lit like a preference file
            //Write more stuff if you want
            writer.close();
            saved = true;
        } catch (IOException ex) {
            //Catch error here and log errors
        }
        return saved;
    }

And To read from it I use FileReader

private boolean loadData(){
        File file = getAndroidFile();
        if(null == file){
            return false;
        }
        boolean read = false;
        try{
            FileReader reader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(reader);
            
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                processDataLine(line); // Read the line and get what you need
            }
            reader.close();
            read = true;
        } catch (IOException ex) {
            //Catch error here and do stuff
        }
        
        return read;
    }

I hope this helps

1 Like

Once again thank you , it works like a charm !!!
You are my Android guru !!! :slight_smile: