删除以“。”开头的文件夹。安卓

时间:2015-07-26 10:23:16

标签: java android directory

我可以使用下面的代码删除特定目录的内容,但我只想删除名称以“。”开头的文件夹/文件。代替。例如:.aptoide,.adobe,.dcim

package com.example.deleter;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        File dir = new File(Environment.getExternalStorageDirectory()+"/CHO/D2");
        if (dir.isDirectory()) {
                String[] children = dir.list();
                for (int i = 0; i < children.length; i++) {
                    new File(dir, children[i]).delete();
                }
            }
    }
}

2 个答案:

答案 0 :(得分:4)

只需Environment.getExternalStorageDirectory()即可获得外部存储的根目录。您可以检查文件名是否以.startsWith开头:

File dir = Environment.getExternalStorageDirectory();
if (dir.isDirectory()) {
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++) {
        if (children[i].startsWith(".")) {
            new File(dir, children[i]).delete();
        }
    }
}

或等同于charAt

if (children[i].charAt(0) == '.') {

答案 1 :(得分:2)

您是否尝试过以下操作:

File dir = new File(Environment.getExternalStorageDirectory()+"/CHO/D2");
if (dir.isDirectory()) {
   String[] children = dir.list();
   for (int i = 0; i < children.length; i++) {
       String name = children[i];
       if (name.startsWith(".") {
           new File(dir, children[i]).delete();
       }
   }
}