我正在开发一个应用程序,它有一个下载几个文件的启动画面,在文件开始下载之前我想检查文件是否已经存在,如果存在我想删除它们。下面显示的代码包含正确的文件路径和检查文件是否存在的函数似乎可以正常工作,因为 Logcat 中的读出状态为“文件已删除”。
然而,当我检查手机本身时,我发现每当我启动应用程序时,都会有 2 个文件添加到文件夹中,文件名相同,但数量不断增加
例如发射 1...我明白了
clientraw.txt
clientrawextra.txt
启动 2...我明白了
clientraw.txt
clientrawextra.txt
clientraw-1.txt
clientrawextra-1.txt
等等......
因此删除功能似乎不起作用,我们将不胜感激!
//Code that checks if the clientraw.txt file already exists, if so the file is deleted
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() +
"/Download", client);
Log.d("file path", String.valueOf(file));
if (file.exists()) {
file.delete();
Log.d("file", "file deleted");
}
File sdCardextra = Environment.getExternalStorageDirectory();
File fileextra = new File(sdCardextra.getAbsolutePath() +
"/Download", clientextra);
if (fileextra.exists()) {
fileextra.delete();
Log.d("file", "file deleted");
}
ready();
似乎删除文件的速度不够快?当我摆脱 ready();
方法(下载文件的方法)时,它确实可以很好地删除文件,所以我认为文件在真正删除以前的文件之前开始下载坚持这个?!
最佳答案
public static boolean deleteDirectory(File path) {
// TODO Auto-generated method stub
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return(path.delete());
}
这段代码会帮助你.. 并且在 Android Manifest 中你必须获得权限才能进行修改..
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
关于android - 删除功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18867058/