JAVA/File

Java 폴더 File Name Check

h4cker 2023. 5. 18. 17:03
SMALL

특정폴더에서 filename을 체크하는 로직이 필요하다고 하면 아래와 같이 코딩을 하시면 됩니다.

 

아래는 간단한 예제입니다.

 

package Foldercheck;
import java.io.File;

public class FileNmCheck {
    public static void main(String[] args) {
        File folder = new File("/temp/upload/");  // Replace with the actual path to your folder
       
        File[] files = folder.listFiles();

        String pattern = "[U].*\\.pdf$";
       
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    boolean matches = file.getName().matches(pattern);
                    System.out.println(matches);
                }
            }
        } else {
            System.out.println("Invalid folder path.");
        }
    }
}

 

소스를 간단히 설명하자면 /temp/upload/ 경로의 폴더를 읽어서 for 루프를 돌며 파일이면 패턴과 일치하는지 확인해서 일치하면 true를 불일치하면 false를 반환해주는 로직입니다.

 

String pattern = "[U].*\\.pdf$";

-> U로 시작하고 확장자가 .pdf로 끝나는 파일을 찾는 regular 패턴입니다.

 

* refrence source : https://gitlab.com/jeongjaeha/file.git

LIST