Java searching file name from the one folder

北战南征 提交于 2019-12-02 18:10:15

问题


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)

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

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

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?


回答1:


// 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
    }
}



回答2:


Probably the easiest way is to simple use File#listFiles(FileFilter), something like

File[] fileList = new File("/path/to/search").listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        return pathname.getName().endsWith(".txt");
    }
});



回答3:


File#getName() should return aString`, then use:

filename.startsWith(...);
filename.endsWith(...);


来源:https://stackoverflow.com/questions/13216432/java-searching-file-name-from-the-one-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!