简体   繁体   中英

Regex for file name containing string anywhere Java

Apologies if this is not worded well..

Basically I have this line in a servlet -

FileInputStream flinp = new FileInputStream("C:\\xampp\\img\\"+empid+".jpg");

where empid is a string.

So currently I am getting files with the empid as the name, but I need to get files that have the empid ANYWHERE in the name.. so for example if my empid is 2500, I need to get the file if its called anything like -

  • 2500_Amy
  • Amy_2500
  • Amy2500
  • 2500Amy

etc.. Can anyone help with this? Is it regex I need to use and if so what do I write? Thanks

I tried this but bringing me an error -

FileInputStream flinp = new FileInputStream("C:\\xampp\\img\\"+.*?empid.*+".jpg");

EDIT -

BTW, in my jsp I have a loop with this line in it so that multiple empid's are passed to the "ReadImage" servlet and multiple images are read.. not sure if this makes my question any different but just to add it anyway -

<img src='<%=request.getContextPath()%>/ReadImages?id<%=thisemp.getEmpGid()%>'

You're going to need to use a FileVisitor and walk the filesystem hierarchy. Use the visitor and your generated regex to filter and collect a list of files that match your criteria.

https://docs.oracle.com/javase/8/docs/api/java/nio/file/FileVisitor.html

A simple solution using old java IO (which I'm inferring from using FileInputStream ) could be:

public static void main(String[] args) throws FileNotFoundException {
    String dirName = "c:/stuff";
    File directory = new File(dirName);
    String[] pathnames = directory.list();

    FileInputStream fis = findFirstMatching(dirName, pathnames, "38");
    if (fis != null) {
        //your code
    }
}

static FileInputStream findFirstMatching(String dirname, String[] pathnames, String empId) throws FileNotFoundException {
    for (String pathname : pathnames) {
        if (Pattern.matches(".*" + empId + ".*", pathname)) {
            return new FileInputStream(dirname + "/" + pathname);
        }
    }
    return null;
}

Try to find required file using Files.walk(...) :

var nameRegEx = ".*" + epid + ".*.jpd";
Optional<Path> path = Files.walk(Paths.get("C:\\xampp\\img\\"))
            .filter(Files::isRegularFile)
            .filter(p -> p.toFile().getName().matches(nameRegEx))
            .findFirst();

You cannot use a regex directly to an FileInputStream , However, you can read all the files and then filter out the required once like below. If reading all can be done in your case,

File folder = new File( "/user/folder/" ); // Base folder where you have all the files
List<File> collectedFiles = Arrays.stream( folder.listFiles() )
                                  .filter( file -> file.getName().contains( "1525" ) ) // Check if filename as your employee number
                                  .collect( Collectors.toList() ); // Get all the filtered files as a list

Another approach is to use the FileNameFilter

FilenameFilter filter = ( dir, name ) -> name.contains( "1525" );
File folder = new File( "/user/folder/" ); // Base folder where you have all the files
List<File> collectedFiles = Arrays.stream( folder.listFiles(filter) )
                                  .collect( Collectors.toList() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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