简体   繁体   中英

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

Ty adding

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

in AndroidManifest.xml file

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

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