简体   繁体   中英

Regex to replace a folder name in poll path in java

I have a relative path to get the files listed in that folder:

folder name: ReadFiles

I just use File pollFile = new File("ReadFiles") to read all the files from that folder.

Now the folder becomes "ReadFiles/201907101418" and folder name with date range varies all the time.

Is there any way to use regular expression to replace that date specific folder and get all the files listen under it?

You can use a FileFilter to check the name of subfolders to match with a pattern:

package be.test;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

public class FileTest {

    public static void main(String[] args) throws IOException {
        File f=new File("ReadFiles");
        File[] datefolders=f.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory() && pathname.getName().matches("20\\d{10}");
            }
        });
        for (File subf:datefolders)
        {
            File[] myfiles=subf.listFiles();
            for (File myfile:myfiles)
            {
                System.out.println("Found file: "+myfile.getAbsolutePath());
                // do your stuff with the files in myfile;
            }
        }
    }
}

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