corneliu
corneliu

Reputation: 685

android app write text file

I have an Android Java application and I am trying to create a file and write something into it:

    try {
        File file = new File( "/storage/emulated/0/text.txt" );
        file.createNewFile();
        FileWriter fwr = new FileWriter( file );
        fwr.write( "something" );
        fwr.close();
    } catch( Exception e ) {
        e.printStackTrace();
    }

When I run the app, this line: file.createNewFile(); gives me the following error: open failed: ENOENT (no such file or directory) probably because I don't have the rights to write there. What am I doing wrong? Where do I have the rights to create a file? I don't want the file to be part of the app, such as a properties file. I want my file to be independent, and inside the home directory of the user.

Edit: When I try to open the file in the Movies directory like this: File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_MOVIES ) + "/movielist.txt" ); I get this error: open failed: EACCESS: Permission denied

Upvotes: 2

Views: 1213

Answers (2)

Elango
Elango

Reputation: 411

try this

AndroidManifest.xml

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

Java source

File root = Environment.getExternalStorageDirectory(); 
File file= new File (root.getAbsolutePath());
try {
    FileOutputStream f = new FileOutputStream(file);
    PrintWriter pw = new PrintWriter(f);
    pw.println("Hi , How are you");
    pw.println("Hello");
    pw.flush();
    pw.close();
    f.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
    Log.i(TAG, "******* File not found. Did you" +
            " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
} catch (IOException e) {
    e.printStackTrace();
}   

Upvotes: 1

AruLNadhaN
AruLNadhaN

Reputation: 2826

If you are want to create a File in the External memory of the user. Then you have to get this permission in the manifest.

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

Then get the path like this code snippet

FileOutputStream fos;
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
String FILENAME =path + "/External"; // External is the text file name
String text = "Hello I am in External!"; // text inside the file
fos=new FileOutputStream(FILENAME);
fos.write(text.getBytes());
fos.close();

Upvotes: 1

Related Questions