简体   繁体   中英

Can't write file txt on android

I try to make sms log, but my device send a error message like this

07-18 10:11:33.956: E/One(1320): Could not write file /sdcard/log.txt (Permission denied)

my code to write file

File root = Environment.getExternalStorageDirectory();
try 
{
    BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/sdcard/log.txt"), true));
    if (root.canWrite()) 
    {
        fw.newLine();
        fw.write("----+ Monitoring SMS +----" + "\n");
        fw.write("- Pesan Masuk "+ "\n");
        fw.write(logSMS + "\n");
        fw.write("          ----+||+----" + "\n");
        fw.newLine();
        fw.close();
    } 
} catch (IOException e) {
    Log.e("One", "Could not write file " + e.getMessage());
}   

my app's manifest permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_MMS" />
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALENDAR"></uses-permission>
<uses-permission android:name="android.permission.READ_CALENDAR"></uses-permission>

I can't find any error, please help me

On some devices sdcard isnt in the root directory.

What you want to do it is the replace "/sdcard/log.txt" with root + "/log.txt" you have the sdcard there but your not using it.

You can't write to the root of the SDCard. Create a folder on your SDCard, and write into that.

http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory ()

can you try replacing

BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/sdcard/log.txt"), true));

with

BufferedWriter fw = new BufferedWriter(new FileWriter(new File(root.getAbsolutePath() + "/log.txt"), true));

This is to make sure that your code is writing to a system assigned external storage path. because it varies between different devices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM