import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ResourceLoader {
private final String configFilePath;
private final Map<String, List<String>> resourceMap = new HashMap<>();
public ResourceLoader(String configFilePath) {
this.configFilePath = configFilePath;
loadResources();
}
private void loadResources() {
File configFile = new File(configFilePath);
if (!configFile.exists()) {
throw new IllegalArgumentException("Config file not found: " + configFilePath);
}
// Assuming config file is a simple key-value pair (e.g., key=resource1,resource2)
try {
java.io.BufferedReader reader = new java.io.FileReader(configFile);
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("=");
if (parts.length == 2) {
String key = parts[0].trim();
String resourcesStr = parts[1].trim();
List<String> resources = new ArrayList<>();
resources.addAll(List.of(resourcesStr.split(","))); // Split by comma
resourceMap.put(key, resources);
}
}
reader.close();
} catch (Exception e) {
throw new RuntimeException("Error loading resources from config file: " + e.getMessage(), e);
}
}
public List<String> getResources(String key) {
return resourceMap.getOrDefault(key, new ArrayList<>()); // Return empty list if key not found
}
public static void main(String[] args) {
//Example Usage:
String configPath = "config.txt";
// Create a sample config file for testing
File configFile = new File(configPath);
try {
java.io.FileWriter writer = new java.io.FileWriter(configFile);
writer.write("images=image1.png,image2.jpg\n");
writer.write("fonts=fontA.ttf,fontB.otf\n");
writer.close();
} catch (Exception e) {
System.err.println("Error creating sample config file: " + e.getMessage());
return;
}
ResourceLoader loader = new ResourceLoader(configPath);
List<String> images = loader.getResources("images");
System.out.println("Images: " + images); //Expected output: Images: [image1.png, image2.jpg]
List<String> fonts = loader.getResources("fonts");
System.out.println("Fonts: " + fonts); //Expected output: Fonts: [fontA.ttf, fontB.otf]
List<String> nonExistent = loader.getResources("nonExistent");
System.out.println("Non existent: " + nonExistent); //Expected output: Non existent: []
}
}
Add your comment