Mohsen fallahi
Mohsen fallahi

Reputation: 917

Deleting file from sdcard in android phone

I want to delete a file named "playerdata.txt" on an SD card. The following code is not working

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

My problem is I want to copy "playerdata.txt" to that folder called GameHacker and I use this code

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);

  }

}

and it works fine but the second time it doesn't replace it and I want to first delete that and then copy and I add the

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

to manifest

Upvotes: 1

Views: 490

Answers (2)

Mallu Don
Mallu Don

Reputation: 112

There may be many reason for file not being deleted. One of them is that your app dont have write permission for sd card. Try to include that permission android:name="android.permission.WRITE_EXTERNAL_STORAGE

Upvotes: 0

Sandhu Santhakumar
Sandhu Santhakumar

Reputation: 1688

Ty adding

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

in AndroidManifest.xml file

Upvotes: 2

Related Questions