Vignesh
Vignesh

Reputation: 3601

Overwrite text file programmatically

I'm trying to overwrite a text file from android application, what I have done yet is,

I have created one text file in one activity using:

FileOutputStream create_file = null;
OutputStreamWriter osw = null;
create_file = openFileOutput("filename.txt", Context.MODE_WORLD_WRITEABLE);
osw = new OutputStreamWriter(create_file);
osw.write("text goes here");
osw.close();
create_file.close();

and I have opened that file in another activity read the contents line by line using:

FileInputStream open_file = openFileInput("filename.txt");
InputStreamReader isr = new InputStreamReader(open_file);
BufferedReader inRd = new BufferedReader(isr);
while ((getText = inRd.readLine()) != null)
{
    Toast.makeText(getApplicationContext(), getText, Toast.LENGTH_SHORT).show();
}

through this I have verified whether the content is stored or not, and made sure that the file exist with the content, but when I try to overwrite that file from another activity using:

FileOutputStream create_file = null;
OutputStreamWriter osw = null;
create_file = new FileOutputStream(new File(PasswordUtil.pswrd_file), false);
osw = new OutputStreamWriter(create_file);
osw.write(getString);

I'm getting one exception,

java.io.FileNotFoundException:/ filename.txt (Read-only file system)

Note: The text file is stored in Internal storage.

Any help, thanks in advance.

Upvotes: 2

Views: 19721

Answers (1)

Vignesh
Vignesh

Reputation: 3601

I found the reason for that FileNotFoundException, its because instead of the following line:

create_file = new FileOutputStream(new File("filename.txt", false));

we have to specify the path for that file, for me, I have stored it in internal storage and I gave the path

"/data/data/<Package-Name>/files/" + "filename.txt"

and I've changed the overwrite coding like this,

FileOutputStream overWrite = new FileOutputStream("/data/data/<Package-Name/files/" + "filename.txt", false);
overWrite.write(getString.getBytes());
overWrite.flush();
overWrite.close();

now all are working well.

Upvotes: 6

Related Questions