Documentation for Creation of Properties File config2.prop Eclipse Java Test Application Project Name: KeyValuePairConfigProject Source Files: 1. ApplicationAttributes.java - the interface for saving and retrieving configuration properties from the config.prop file. 2. KeyValuePair.java - the class that provides the key-value pairs to the ApplicationAttributes.java class for creation and saving the configuration properties. 1. Use an interface to enter the configuration properties that are to be stored in the config.prop properties file. The file must reside inside the directory containing the application, otherwise the path to the config file would need to be appropriately modified to assure it can be accessed. The classes, ApplicationAttributes.java and KeyValuePair.java need to be included in the application associated with the configuration. The code below illustrates saving three key-value pairs. All the key-values need to be created at once, otherwise the file config file needs to copied into memory and saved with each new property. This set of code assumes all the properties can be established at once and saved with the code below. This approach substitutes having to create a text file and saving it manually. It assumes the code is within a Swing interface where a button is clicked, but can be initiated anywhere in the startup of the application before the file is required: public void widgetSelected(SelectionEvent e) { // assumes a button click initiates the file creation... // btnInitializeProperties clicked // btnInit clicked - the key-values will be from interface objects // filled by selecting FileFind or user input to textFields. //0. Set the PropertyFilePath: String propertyFilePath = "config2.prop"; // 1. String key1 = "path.localPath"; String value1 = "D:/"; //2. String key2 = "path.musicScoresPath"; String value2 = "I:/root/musicscores/purePDF"; // 3. String key3 = "category.composer"; String value3 = "Yoshimatsu"; // place text keys and values into String args for KeysValuesTOArray class // where the pairs will be saved to the configuration file: String keys[] = {key1, key2, key3 }; String values[] = { value1, value2, value3 }; ApplicationAttributes attributes = new ApplicationAttributes(); attributes.keyValuePairsToArray(propertyFilePath, keys, values); } Retrieving the three properties: Each time a retrieval needs to be made, the file name is passed to ApplicationAttributes unless the calling function maintains the visibility throughout any other calls to the config file. The calls below are assumed to be from separate isolated functions throughout the body of the application: a. Obtain the value of path.musicScoresPath: ApplicationAttributes attributes = new ApplicationAttributes(); attributes.setPropertiesFilePath("config2.prop"); String value = attributes.getPropertyWithKey("path.musicScoresPath"); System.out.println("Passed Key = path.musicScoresPath - Value = " + value); b. Obtain the value of path.localPath: ApplicationAttributes attributes = new ApplicationAttributes(); attributes.setPropertiesFilePath("config2.prop"); String value = attributes.getPropertyWithKey("path.localPath"); System.out.println("Passed Key = path.localPath - Value = " + value); c. Obtain the value of category.composer: ApplicationAttributes attributes = new ApplicationAttributes(); attributes.setPropertiesFilePath("config2.prop"); String value = attributes.getPropertyWithKey("category.composer"); System.out.println("Passed Key = category.composer - Value = " + value); ======================================= Source Code 1. ===================================== ApplicationAttributes.jfava import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Properties; public class ApplicationAttributes { //Path propertiesPath = Path.of("config2.prop"); private String propertiesFilePath; public void keyValuePairsToArray(String pPropertyFilePath, String pKeyArgs[], String pValueArgs[]) { ArrayList list = new ArrayList(); for(int i = 0; i < (pKeyArgs.length); i++) { list.add(new KeyValuePair(pKeyArgs[i], pValueArgs[i])); } for(int i = 0; i < (pKeyArgs.length); i++) { KeyValuePair kvp = list.get(i); System.out.println(kvp.toString()); } System.out.println("Config file: " + pPropertyFilePath); System.out.println(" Passing the pairs to ApplicationAttributes to SAVE THE KEY-VALUE PAIRS TO CONFIG FILE"); //ApplicationAttributes appAttributes = new ApplicationAttributes(); this.setPropertiesFilePath(pPropertyFilePath); this.saveAttributes(list); } public void setPropertiesFilePath(String pPropertiesFilePath) { propertiesFilePath = pPropertiesFilePath; } public String getPropertiesFilePath() { return this.propertiesFilePath; } public void saveAttributes(ArrayList pKeyValuePairsList) { Properties props = new Properties(); System.out.println("In KeysValuesArrays class/ testStringArrayValues"); for(int i = 0; i < pKeyValuePairsList.size(); i++) { KeyValuePair kvp = pKeyValuePairsList.get(i); props.setProperty(kvp.getKey(), kvp.getValue()); System.out.println(kvp.toString()); } FileOutputStream fos = null; try { fos = new FileOutputStream(this.getPropertiesFilePath()); System.out.println("INSIDE new FileOutputStream(" + this.getPropertiesFilePath() + ")"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { props.store(fos, "Application-Configuration"); System.out.println("Succesfully executed: props.store(fos,Application-Configuration)"); } catch (IOException e) { System.out.println("Failed to execute: props.store(fos,Application-Configuration)"); e.printStackTrace(); } } public void deleteIfExists (Path propertiesPath ) { try { if (Files.deleteIfExists(propertiesPath)) { System.out.println("Properties file, " + propertiesPath + " deleted successfully."); } else { System.out.println("Properties file did not exist."); } } catch (java.io.IOException e) { System.err.println("Error deleting properties file: " + e.getMessage()); } } public void readAttributes() { // 2. Reading Properties File: // a. Create a Properties object. // b. Create an InputStream (e.g., FileInputStream) from the attribute file. // c. Call load(InputStream in) to load the properties from the file. // d. Use getProperty(String key) to retrieve the value associated with a key. Properties props = new Properties(); try (FileInputStream fis = new FileInputStream(this.getPropertiesFilePath())) { props.load(fis); String localPath = props.getProperty("path.localPath"); String musicScoresPath = props.getProperty("path.musicScoresPath"); String category = props.getProperty("category.composer"); System.out.println("localPath: " + localPath); System.out.println("musicScoresPath: " + musicScoresPath); System.out.println("category: " + category); } catch (IOException e) { e.printStackTrace(); } } public void addNewAttribute() { String filePath = this.getPropertiesFilePath(); // Name of your properties file Properties properties = new Properties(); // 1. Load the existing properties file try (FileInputStream fis = new FileInputStream(filePath)) { properties.load(fis); } catch (IOException e) { System.err.println("Error loading properties file: " + e.getMessage()); // If the file doesn't exist, a new one will be created when saving } // 2. Add a new key-value pair properties.setProperty("new.key", "new_value_added"); properties.setProperty("another.setting", "true"); // Example of adding another // 3. Save the updated properties back to the file try (FileOutputStream fos = new FileOutputStream(filePath)) { properties.store(fos, "Updated properties file"); System.out.println("New value added and properties saved successfully."); } catch (IOException e) { System.err.println("Error saving properties file: " + e.getMessage()); } } public String getPropertyWithKey(String pKey) { // 2. Reading Properties File: // a. Create a Properties object. // b. Create an InputStream (e.g., FileInputStream) from the attribute file. // c. Call load(InputStream in) to load the properties from the file. // d. Use getProperty(String key) to retrieve the value associated with a key. System.out.println("GetPropertyWithKey - file path = " + this.getPropertiesFilePath()); Properties props = new Properties(); String value = ""; try (FileInputStream fis = new FileInputStream(this.getPropertiesFilePath())) { props.load(fis); value = props.getProperty(pKey); } catch (IOException e) { e.printStackTrace(); } return value; } } 2. ===================================== KeyValuePair.java public class KeyValuePair { private String key; private String value; public KeyValuePair(String pKey, String pValue) { // constructor returns object this.key = pKey; this.value = pValue; } public String getKey() { return this.key; } public String getValue() { return this.value; } @Override public String toString() { return "KeyValuePair [key=" + key + ", value=" + value + "]"; } } 3. ===================================== SwingInterface.java import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; public class SwingInterface { protected Shell shell; /** * Launch the application. * @param args */ public static void main(String[] args) { try { SwingInterface window = new SwingInterface(); window.open(); } catch (Exception e) { e.printStackTrace(); } } /** * Open the window. */ public void open() { Display display = Display.getDefault(); createContents(); shell.open(); shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /** * Create contents of the window. */ protected void createContents() { shell = new Shell(); shell.setSize(450, 430); shell.setText("SWT Application"); shell.setLayout(null); Button btnInitializeProperties = new Button(shell, SWT.NONE); btnInitializeProperties.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // btnInitializeProperties clicked // btnInit clicked - the key-values will be from interface objects // filled by selecting FileFind or user input to textFields. //0. Set the PropertyFilePath: String propertyFilePath = "config2.prop"; // 1. String key1 = "path.localPath"; String value1 = "D:/"; //2. String key2 = "path.musicScoresPath"; String value2 = "I:/root/musicscores/purePDF"; // 3. String key3 = "category.composer"; String value3 = "Yoshimatsu"; // place text keys and values into String args for KeysValuesTOArray class // where the pairs will be saved to the configuration file: String keys[] = {key1, key2, key3 }; String values[] = { value1, value2, value3 }; ApplicationAttributes attributes = new ApplicationAttributes(); attributes.keyValuePairsToArray(propertyFilePath, keys, values); } }); btnInitializeProperties.setBounds(24, 50, 213, 30); btnInitializeProperties.setText("Initialize Properties"); Button btnTestKeyValue = new Button(shell, SWT.NONE); btnTestKeyValue.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //btnTestKeyValue clicked - get the associated value with key passed ApplicationAttributes attributes = new ApplicationAttributes(); attributes.setPropertiesFilePath("config2.prop"); String value = attributes.getPropertyWithKey("path.musicScoresPath"); System.out.println("Passed Key = path.musicScoresPath - Value = " + value); } }); btnTestKeyValue.setBounds(72, 132, 284, 30); btnTestKeyValue.setText("pass key - path.musicScoresPath"); Button btnNewButton = new Button(shell, SWT.NONE); btnNewButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ApplicationAttributes attributes = new ApplicationAttributes(); attributes.setPropertiesFilePath("config2.prop"); String value = attributes.getPropertyWithKey("path.localPath"); System.out.println("Passed Key = path.localPath - Value = " + value); } }); btnNewButton.setBounds(72, 207, 284, 30); btnNewButton.setText("pass key - path.localPath"); Button btnNewButton_1 = new Button(shell, SWT.NONE); btnNewButton_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ApplicationAttributes attributes = new ApplicationAttributes(); attributes.setPropertiesFilePath("config2.prop"); String value = attributes.getPropertyWithKey("category.composer"); System.out.println("Passed Key = category.composer - Value = " + value); } }); btnNewButton_1.setBounds(72, 278, 284, 30); btnNewButton_1.setText("pass key - category.composer"); } }