简体   繁体   English

在Android手机中从SD卡删除文件

[英]Deleting file from sdcard in android phone

I want to delete a file named "playerdata.txt" on an SD card. 我想删除SD卡上名为“ playerdata.txt”的文件。 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 我的问题是我想将“ 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);

  }

}

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 Ty添加

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

in AndroidManifest.xml file 在AndroidManifest.xml文件中

There may be many reason for file not being deleted. 可能有很多原因导致文件未被删除。 One of them is that your app dont have write permission for sd card. 其中之一是您的应用没有对SD卡的写入权限。 Try to include that permission android:name="android.permission.WRITE_EXTERNAL_STORAGE 尝试包含该权限android:name =“ android.permission.WRITE_EXTERNAL_STORAGE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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