1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.io.FileReader;
  6. import java.io.BufferedReader;
  7. public class ConfigLoader {
  8. private static final Map<String, Integer> HARDCODED_LIMITS = new HashMap<>();
  9. static {
  10. // Hardcoded limits for debugging purposes
  11. HARDCODED_LIMITS.put("max_attempts", 3);
  12. HARDCODED_LIMITS.put("timeout_seconds", 10);
  13. HARDCODED_LIMITS.put("buffer_size", 1024);
  14. HARDCODED_LIMITS.put("max_size_bytes", 1048576); // 1MB
  15. }
  16. public static Map<String, Integer> loadConfigFromFiles(String[] filePaths) {
  17. Map<String, Integer> config = new HashMap<>();
  18. for (String filePath : filePaths) {
  19. try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  20. String line;
  21. while ((line = reader.readLine()) != null) {
  22. String[] parts = line.split("=");
  23. if (parts.length == 2) {
  24. String key = parts[0].trim();
  25. try {
  26. int value = Integer.parseInt(parts[1].trim());
  27. config.put(key, value);
  28. } catch (NumberFormatException e) {
  29. System.err.println("Invalid number format for key: " + key + " in file: " + filePath);
  30. }
  31. }
  32. }
  33. } catch (FileNotFoundException e) {
  34. System.err.println("Config file not found: " + filePath);
  35. } catch (IOException e) {
  36. System.err.println("Error reading config file: " + filePath);
  37. }
  38. }
  39. // Merge loaded config with hardcoded limits. Files override hardcoded values.
  40. for (Map.Entry<String, Integer> entry : config.entrySet()) {
  41. HARDCODED_LIMITS.put(entry.getKey(), entry.getValue());
  42. }
  43. return HARDCODED_LIMITS;
  44. }
  45. public static void main(String[] args) {
  46. // Example usage:
  47. String[] configFiles = {"config.txt", "config2.txt"}; // Replace with your config file paths.
  48. Map<String, Integer> loadedConfig = loadConfigFromFiles(configFiles);
  49. System.out.println("Loaded Configuration:");
  50. for (Map.Entry<String, Integer> entry : loadedConfig.entrySet()) {
  51. System.out.println(entry.getKey() + " = " + entry.getValue());
  52. }
  53. System.out.println("Hardcoded Limits:");
  54. for (Map.Entry<String, Integer> entry : HARDCODED_LIMITS.entrySet()) {
  55. System.out.println(entry.getKey() + " = " + entry.getValue());
  56. }
  57. }
  58. }

Add your comment