【问题标题】:Deleting file from sdcard in android phone从 android 手机的 sdcard 中删除文件
【发布时间】:2013-08-16 17:52:44
【问题描述】:

我想删除 SD 卡上名为“playerdata.txt”的文件。以下代码无效

{
    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>

表现出来

【问题讨论】:

  • 我认为文件路径错误..
  • 试试这个File file = new File(android.os.Environment.getExternalStorageDirectory(),"/GameHacker/playerdata.txt"); if(file.exists()) { file.delete(); } 并确保你的清单中有uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE

标签: java android file-io android-sdcard delete-file


【解决方案1】:

添加

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

在 AndroidManifest.xml 文件中

【讨论】:

    【解决方案2】:

    文件未被删除的原因可能有很多。其中之一是您的应用程序没有 sd 卡的写入权限。尝试包含该权限 android:name="android.permission.WRITE_EXTERNAL_STORAGE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多