我如何删除和重命名 Android 中的文件?

How can i delete and rename a file in Android?

您好,我一直在寻找删除或重命名手机内部存储中特定文件的方法。具体来说,我的目标是 waze 文件夹中的文件,这些文件位于内部存储的根文件夹中。正如我所说,我正在寻找有关此的更多信息,但对我没有任何帮助,所以我认为我的错误可能出在我正在使用的路径中。这是我的代码:

重命名:

    file_Path = "/data/data/waze"
    File from      = new File(file_Path, "currentFileName");
    File to        = new File(file_Path, "newFilename");
    from.renameTo(to); //this method returns me False

要删除:

file_Path ="/data/data/waze/file"
File file = new File(file_Path);
boolean deleted = file.delete();

我尝试了很多方法来做到这一点,但这是我认为最接近实现的方法。因此,如果你们中的任何人都可以指出我的 mistake/s,我将感谢您!来自哥斯达黎加的拥抱!

除您自己的应用文件外,您没有对 internal storage 上文件的读取或写入权限。您不能从其他应用程序(例如 Waze)重命名或删除文件。

例外情况是,在获得 root 权限的设备上,您可以要求派生具有超级用户权限的进程,这些进程将具有 device-wide read/write 访问权限。

为了完成@CommonsWare 的回答,您可以检查设备是否已root,然后执行方法或其他操作。

这是一个例子,

摘自 : http://www.stealthcopter.com/blog/2010/01/android-requesting-root-access-in-your-app/

Process p; 
try { 
   // Preform su to get root privledges
   p = Runtime.getRuntime().exec("su"); 
   
   // Attempt to write a file to a root-only 
   DataOutputStream os = new DataOutputStream(p.getOutputStream()); 
   os.writeBytes("echo \"Do I have root?\" >/system/sd/temporary.txt\n");
   
   // Close the terminal
   os.writeBytes("exit\n"); 
   os.flush(); 
   try { 
      p.waitFor(); 
           if (p.exitValue() != 255) { 
              // TODO Code to run on success
              toastMessage("root");
           } 
           else { 
               // TODO Code to run on unsuccessful
               toastMessage("not root");    
           } 
   } catch (InterruptedException e) { 
      // TODO Code to run in interrupted exception
       toastMessage("not root"); 
   } 
} catch (IOException e) { 
   // TODO Code to run in input/output exception
    toastMessage("not root"); 
}

或者你可以看看:

http://su.chainfire.eu/#how

https://github.com/Chainfire/libsuperuser

此外,在您的清单中也使用以下权限:

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

或者 Github 上有一个很好的例子:

https://github.com/mtsahakis/RootChecker