1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. public class ResourceLoader {
  7. private final String configFilePath;
  8. private final Map<String, List<String>> resourceMap = new HashMap<>();
  9. public ResourceLoader(String configFilePath) {
  10. this.configFilePath = configFilePath;
  11. loadResources();
  12. }
  13. private void loadResources() {
  14. File configFile = new File(configFilePath);
  15. if (!configFile.exists()) {
  16. throw new IllegalArgumentException("Config file not found: " + configFilePath);
  17. }
  18. // Assuming config file is a simple key-value pair (e.g., key=resource1,resource2)
  19. try {
  20. java.io.BufferedReader reader = new java.io.FileReader(configFile);
  21. String line;
  22. while ((line = reader.readLine()) != null) {
  23. String[] parts = line.split("=");
  24. if (parts.length == 2) {
  25. String key = parts[0].trim();
  26. String resourcesStr = parts[1].trim();
  27. List<String> resources = new ArrayList<>();
  28. resources.addAll(List.of(resourcesStr.split(","))); // Split by comma
  29. resourceMap.put(key, resources);
  30. }
  31. }
  32. reader.close();
  33. } catch (Exception e) {
  34. throw new RuntimeException("Error loading resources from config file: " + e.getMessage(), e);
  35. }
  36. }
  37. public List<String> getResources(String key) {
  38. return resourceMap.getOrDefault(key, new ArrayList<>()); // Return empty list if key not found
  39. }
  40. public static void main(String[] args) {
  41. //Example Usage:
  42. String configPath = "config.txt";
  43. // Create a sample config file for testing
  44. File configFile = new File(configPath);
  45. try {
  46. java.io.FileWriter writer = new java.io.FileWriter(configFile);
  47. writer.write("images=image1.png,image2.jpg\n");
  48. writer.write("fonts=fontA.ttf,fontB.otf\n");
  49. writer.close();
  50. } catch (Exception e) {
  51. System.err.println("Error creating sample config file: " + e.getMessage());
  52. return;
  53. }
  54. ResourceLoader loader = new ResourceLoader(configPath);
  55. List<String> images = loader.getResources("images");
  56. System.out.println("Images: " + images); //Expected output: Images: [image1.png, image2.jpg]
  57. List<String> fonts = loader.getResources("fonts");
  58. System.out.println("Fonts: " + fonts); //Expected output: Fonts: [fontA.ttf, fontB.otf]
  59. List<String> nonExistent = loader.getResources("nonExistent");
  60. System.out.println("Non existent: " + nonExistent); //Expected output: Non existent: []
  61. }
  62. }

Add your comment