14 Haziran 2023 Çarşamba

SpringContext PathMatchingResourcePatternResolver Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
Kalıtım şöyle
  ResourcePatternResolver
    PathMatchingResourcePatternResolver

getResource metodu
Resource döner
Örnek - classpath
Şöyle yaparız
@Component public class ValidationUtil { private final ResourcePatternResolver resourcePatternResolver; public ValidationUtil(ResourcePatternResolver resourcePatternResolver) { this.resourcePatternResolver = resourcePatternResolver; } public void readResource() { String path = "classpath:schema/user_details-country.json"; Resource resource = resourcePatternResolver.getResource(path); if (!resource.exists()) { ... } try (InputStream schemaStream = resource.getInputStream()) { ... } catch (Exception e) { ... } } }
getResources metodu
Resource[] döner.

1. classpath: olarak kullanırsak  src/main/resources altında belirtilen örüntüye uyan dosyaları arar
2. file: olarak kullanırsak  belirtilen örüntüye uyan dosyaları arar

Örnek - classpath
Şöyle yaparızsrc/main/resources/csv altındaki dosyalara erişiriz
@Component  
public class CsvUpsertCallback implements Callback {  
  @Autowired  
  private ResourceLoader resourceLoader;  

  // Get the path to the CSV directory  
  PathMatchingResourcePatternResolver resolver = 
    new PathMatchingResourcePatternResolver(resourceLoader);  
  Resource[] resources = resolver.getResources("classpath:csv/*");  
  List<File> files = new ArrayList<>();  
  for (Resource resource : resources) {  
    File file = resource.getFile();  
    if (file.getName().toLowerCase().endsWith(".csv")){  
      files.add(file);  
    }  
  }  
}
Örnek - "file:/path/to/folder/*.sql"
Şöyle yaparız
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources(ExecuteSqlScriptRunner.BASE_SCRIPT_FOLDER +
dirName + "/*.sql");

Hiç yorum yok:

Yorum Gönder