2012-03-23 58 views
0

我想检查我的SD卡根目录中以“thisfile”开头的文件并返回int或字符串中的文件数量。检查以字符串开头的文件数

,比如我有我的SD卡上的10个文件,名称如下:

thisfile1.txt 
thisfile444.txt 
thisfileffvdfv.txt 
thisfilefdfvdfv.txt 
thisfile4fvdfv.txt 
thisfilefvdfvdf.txt 
thisfiledfvdfvdfv.txt 
thisfilefdvdfvdf.txt 
thisfilewedwed.txt 
thisfilewedwedfff.txt 

在这个例子中,我希望我的代码返回10本。

有人可以帮忙吗?

回答

1
File dir = new File(Environment.getExternalStorageDirectory()); 
    int num=0; 
    String[] children = dir.list(); 
    if (children == null) { 
     // Either dir does not exist or is not a directory 
    } else { 
     for (int i=0; i<children.length; i++) { 
      // Get filename of file or directory 
      String filename = children[i]; 
      if(filename.startsWith("thisfile") 
       num++; 
     } 
    } 

System.out.println("total number "+num); 
0
int numberOfFiles=0; 
    File dir = Environment.getExternalStorageDirectory(); 
    String[] children = dir.list(); 
    for (int i = 0; i < children.length; i++) { 
     if (children[i].startsWith("file") 
     numberOfFiles++; 
} 
0

你可以这样做:directory.list()让你的当前目录下的文件名。 你通过你的文件的阵列,并检查文件名中包含“thisfile”使用

String.contains(CharSequence cs) 

每次包含方法返回true,则增加一个变量,它会的次数,你已经找到的文件的名称序列“thisfile”在目录

+0

这很接近,但它可能会返回误报 - 如果'cs'在'String'对象中但不在开头,它仍然会返回true。 – edthethird 2012-03-23 16:52:53

+0

是的,我读得太快了,没有注意到子字符串必须位于文件名的开头。 – 2012-03-23 21:05:46

0

使用的FilenameFilter过滤掉文件第一:

class MyFilter implements FilenameFilter { 

    public boolean accept(File dir, String name) { 

      return (name.startsWith("thisfile")); 

    } 

内,您的活动中使用:

private static final String MEDIA_PATH = new String("/sdcard/"); 
File home = new File(MEDIA_PATH); 
int counter =home.listFiles(new MyFilter()).length 
相关问题