2012-03-13 77 views
-1

我不知道如果我问的问题100%正确的,但这里有云: 我得到这个代码:获取文件名

File root = Environment.getExternalStorageDirectory(); 
File saveFolder= new File(Root, "Save"); 

     String[] files=saveFolder.list(
      new FilenameFilter() { 
       public boolean accept(File dir, String name) { 
       //define here you filter condition for every single file 
        return name.startsWith("1_"); 

       } 
      }); 

     if(files.length>0) { 
      System.out.println("FOUND!"); 
      System.out.println("Files length = "+files.length); 
     } else { 
      System.out.println("NOT FOUND!"); 
     } 

我有2个文件,与"1_"开始,该println还显示我有2个文件。 但是,如何在布尔值之后打印或查看这两个文件的文件名?

因此,像(之间的其他System.out.println):

System.out.println("File names = "+files.names);

+1

可以请你不要再以大写字母开始的变量的名称? – njzk2 2012-03-13 09:58:13

+0

我为你做了 - 下次:**永远不要**使用在SO中发布的代码中以大写字母开头的变量名称。 (..如果你想让人们看你的代码;)) – 2012-03-13 10:00:40

+0

好的,下次我会更加关注。 感谢您的所有答案 – Bigflow 2012-03-13 10:10:48

回答

5

循环阵列上:

String[] files=SaveFolder.list(...); 
for (String name : files) { 
    System.out.println("File name: " + name); 
} 

注意变量的命名约定是与较低的情况下启动它们。

+0

谢谢,从来不知道你可以做这样的循环?这只是我认为的java(从未在C++中看到/使用过) – Bigflow 2012-03-13 10:11:50

+0

这是for-each循环:http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html您可以用普通的循环来做。 – MByD 2012-03-13 10:13:26

0

您可以使用

file.getName(); // for the name of the file 
file.getAbsolutePath(); for the full path of the file 
1

更换

public boolean accept(File dir, String Name) { 
      //define here you filter condition for every single file 
       return Name.startsWith("1_"); 

      } 

与此:

public boolean accept(File dir, String Name) { 
      //define here you filter condition for every single file 
       boolean b = Name.startsWith("1_"); 
       if (b) 
        System.out.println(Name); 
       return b; 

      } 
1

使用Arrays.asList()如果你想快速打印出一个基本数组

System.out.println(Arrays.asList(files)); 
+0

亚当,非常感谢。 – pudaykiran 2014-08-01 05:21:10

1

添加一些代码,if块:

if(files.length>0) { 
    System.out.println("FOUND!"); 
    System.out.println("Files length = "+files.length); 
    // next lines print the filenames 
    for (String fileName:files) 
     System.out.println(fileName); 
} 
0

这是我个人使用的,如果我需要在文件名加载函数来加载。

public void getFiles(String path){ 
     //Store the filesnames to ArryList<String> 
     File dir = new File(path); 
      ArrayList<String> savefiles = new ArrayList<String>(); 
     for(File file : dir.listFiles()){ 
      savefiles.add(file.getName()); 
     } 
     //Check if the filenames or so to say read them 
     for (int i = 0; i < savefiles.size(); i++){ 
      String s = savefiles.get(i); 
      System.out.println("File "+i+" : "+s); 
     } 
     System.out.println("\n"); 
    } 

我希望这有助于C: