2013-08-16 62 views
1

我想刪除SD卡上名爲「playerdata.txt」的文件。下面的代碼是不工作從Android手機的SD卡中刪除文件

{ 
    File file = new File("/sdcard/GameHacker/playerdata.txt"); 
    file.delete(); 
} 

我的問題是我要複製「playerdata.txt」,以所謂的GameHacker該文件夾,我用這個代碼

Context Context = getApplicationContext(); 

String DestinationFile = "/sdcard/GameHacker/playerdata.txt"; 
if (!new File(DestinationFile).exists()) { 
    try { 
    CopyFromAssetsToStorage(Context, "playerdata", DestinationFile); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
} 
} 

private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException { 
    InputStream IS = Context.getAssets().open(SourceFile); 
    OutputStream OS = new FileOutputStream(DestinationFile); 
    CopyStream(IS, OS); 
    OS.flush(); 
    OS.close(); 
    IS.close(); 
} 
private void CopyStream(InputStream Input, OutputStream Output) throws IOException { 
    byte[] buffer = new byte[5120]; 
    int length = Input.read(buffer); 
    while (length > 0) { 
    Output.write(buffer, 0, length); 
    length = Input.read(buffer); 

    } 

} 

,它工作正常,但第二次它不會取代它,我想先刪除然後複製我添加

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

體現

+0

我相信,文件路徑是錯誤的... – sanbhat

+0

試試這個'檔案文件=新的文件(android.os.Environment.getExternalStorageDirectory()」/GameHacker/playerdata.txt「); if(file.exists()) file.delete(); }'並確保您有'使用權限android:name =」android.permission.WRITE_EXTERNAL_STORAGE'清單 – Raghunandan

回答

2

泰添加

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

文件

+0

謝謝你的回答,但我已經完成了 – Mahfa

0

可能有很多原因,未爲文件被刪除。其中之一是你的應用程序沒有SD卡的寫入權限。嘗試包括權限 機器人:名字=「android.permission.WRITE_EXTERNAL_STORAGE

+0

謝謝你的回答,但我已經將它添加到清單 – Mahfa