android - file.delete() 从 android 内部存储返回 false

标签 android file file-io android-file internal-storage

我有一种方法可以从 url 下载图像并将其保存在内部存储的文件夹中

 public void saveDynamicImage(String url,String fileName, String folderName) {

    InputStream iStream;

    BufferedInputStream buffInputStream;
    ByteArrayBuffer byteArray = null;

    try {
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = httpClient.execute(httpGet);
        iStream = httpResponse.getEntity().getContent();

        buffInputStream = new BufferedInputStream(iStream, 8 * 1024);
        byteArray = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = buffInputStream.read()) != -1) {
            byteArray.append((byte) current);
        } 

    } catch (ClientProtocolException e1) {
    } catch (IOException e1) {
    }

    File dynamicImageDir = context.getDir(AppConstants.DYNAMIC_IMAGE, Context.MODE_PRIVATE);
    File appNamefileDir = new File(dynamicImageDir, BaseActivity.appDataStore.getAppName());
    appNamefileDir.mkdirs();
    File controlNameDir = new File(appNamefileDir, folderName);
    controlNameDir.mkdirs();
    File file = new File(controlNameDir, fileName);

    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(byteArray.toByteArray());
        outputStream.close();
        System.out.println("DynamicImage saving over!..");
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}

我想在某个时间点删除整个目录。我删除整个目录的方法是

public void deleteDynamicImage() throws NullPointerException,FileNotFoundException {
    File rootDirectory = context.getDir(AppConstants.DYNAMIC_IMAGE, Context.MODE_WORLD_WRITEABLE);
    boolean status = rootDirectory.delete();
    Log.e("", "delete : "+status);

}

我的状态为“假”。文件已创建并且工作正常。唯一的问题是删除。有什么我想念的吗?

最佳答案

你的文件是目录吗?

如果是,您需要先删除此文件夹中的文件
这段代码运行良好

public void deleteDirectory(File file) {
    if( file.exists() ) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for(int i=0; i<files.length; i++) {
                if(files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                }
                else {
                    files[i].delete();
                }
            }
        }
            file.delete();
    }
}

关于android - file.delete() 从 android 内部存储返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21750499/

相关文章:

android - 从 Google Play 获取付费应用的购买 token

android - 这个关于 VSS/RSS/PSS/USS 的解释准确吗?

windows - 为什么我只能在 Windows 上使用 Tie::File 打开 2045 个文件?

c# - XML 尽可能高效地查找特定元素

android - 在 Android 上以编程方式安装应用程序

file - 如何在静态Web服务器中处理JSON?

javascript - 如何使用 JavaScript 检查文件是否存在?

Java 只打开 BufferedWriter 一次但多次重写内容

unix - UNIX 中文件追加是原子的吗?

android - 高于 2dp 的高度会导致按钮消失