Java从一个文件夹中搜索文件名 [英] Java searching file name from the one folder

查看:430
本文介绍了Java从一个文件夹中搜索文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java,我不太确定搜索文件的方法。我想构建返回文件名的函数(文件名应以 star 开头,以 .txt 结尾)

I am studying Java and I am not really sure the way to searching file. I would like to build the function which returning file names ( the files name should begin with star and end with .txt)

例如,在文件夹中我们有一些带有文件的Java源文件。例如,文件:

For example, in the folder we have Java source file with some file. For example, files:


  • 1.txt

  • 2.txt

  • 4.txt

  • start.txt

  • star.txt

  • onstart.txt

  • starton.txt

  • myjava.java

  • 1.txt
  • 2.txt
  • 4.txt
  • start.txt
  • star.txt
  • onstart.txt
  • starton.txt
  • myjava.java

然后我想得到 start.txt star.txt & starton.txt

Then I would like to get the start.txt, star.txt & starton.txt

我一直在寻找 FilenameFilter 但我无法找到找到文件的好方法。有没有人知道查找文件的方法?

I was looking for the FilenameFilter but I wasn't able to find to good way to find file. Does any one know the way to find files?

推荐答案

// You'll need this import: import java.io.File;

File folder = new File("C:/Folder_Location");
// gets you the list of files at this folder
File[] listOfFiles = folder.listFiles();
// loop through each of the files looking for filenames that match
for(int i = 0; i < listOfFile.length; i++){
    String filename = listOfFiles[i].getName();
    if(filename.startsWith("Stuff") && listOfFiles[i].getName().endsWith("OtherStuff")){
        // do something with the filename
    }
}

这篇关于Java从一个文件夹中搜索文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆