Writing and reading a string to internal storage on Android

I want to write to a file and then read it. When using the openFileOutput (.., ..) method, I understand that this method is not defined as an abstract method. Then I tried it with passing the context using getBaseContext (); and the warning was turned off, but I do not get the result when reading the output. I also tried passing the context as a parameter in the constructor, but that also didn't help. I want to write static methods, so I don’t need to instantiate the class every time, and static are not the reason, because I tried without it. Below is a snippet of code.

Does any path need to be specified even when using internal storage? Is there permission to write files to internal storage? (I have enabled write permission on external storage)

public static void write (String filename,Context c,String string) throws IOException{
    try {
        FileOutputStream fos =  c.openFileOutput(filename, Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


public static String read (String filename,Context c) throws IOException{

    StringBuffer buffer = new StringBuffer();

    FileInputStream fis = c.openFileInput(filename);
    BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
    if (fis!=null) {                            
        while ((Read = reader.readLine()) != null) {    
            buffer.append(Read + "\n" );
        }               
    }       
    fis.close();
    return Read;
}
+5
source share
2 answers

return buffer.toString () in the read method solves the problem. Thanks to Stefan.

+2
source

Is there permission to write files to internal storage?

"You do not need permissions to save files in internal memory. Your application always has permission to read and write files in the internal storage directory."

You can see some posts that say: "android.permission.WRITE_INTERNAL_STORAGE"

There is no such permission ; "WRITE_INTERNAL_STORAGE"

+1
source

All Articles