简体   繁体   English

使用JFileChooser获取目录中的所有文件名?

[英]Get all file names in directory using JFileChooser?

I'm using this bit of code: 我正在使用这段代码:

 fileBrowser() {
      String toReturn = null;
      JFileChooser Chooser = new JFileChooser();
      int choosen = Chooser.showOpenDialog(fileBrowser.this);
      if (choosen == JFileChooser.APPROVE_OPTION) {         
            System.out.println(Chooser.getCurrentDirectory().toString()+"\\"+Chooser.getSelectedFile().getName());
      }

  }

To get the selected file name and location, which is all working fine. 获取所选的文件名和位置,这一切都正常。 I was wondering as an addition, is there also a way to get all the filenames in that directory as well? 我想知道作为一个补充,还有一种方法来获取该目录中的所有文件名吗? something like .getAllFiles() I've had a search around and can't find one? .getAllFiles()类的东西我有一个搜索,找不到一个?

Thanks in Advance. 提前致谢。

Sure, use 当然,使用

File[] filesInDirectory = chooser.getCurrentDirectory().listFiles();

Then you can iterate over that array: 然后你可以遍历那个数组:

for ( File file : filesInDirectory ) {
    System.out.println(file.getName());
}

Well, there's File.list() . 好吧,有File.list() This will list all files by their name from the specified directory (ie File ). 这将按指定目录(即File )的名称列出所有文件。 But this will also return directory names. 但这也将返回目录名称。 In order to circumvent that, use the other File.list(FilenameFilter filter) method that will enable you to filter out directories from the listing. 为了避免这种情况,请使用另一个File.list(FilenameFilter filter)方法,该方法可以从列表中过滤掉目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM