Search code examples
javareplacehashmapbufferstr-replace

Replacing values from HashMap in a file with Java


i'm stuck on this part. The aim is to take the values from an file.ini with this format

X = Y
X1 = Y1
X2 = Y2

take the Y values and replace them in a scxml file instead of the corresponding X keys, and save the new file.scxml

As you can see from my pasted code, i use the HashMap to take the key and values printed correctly, that although it seems right the code to replace the values works only for the first entry of the HashMap.

The code is currently as follows:

public String getPropValues() throws IOException {
        try {
            Properties prop = new Properties();         
            String pathconf = this.pathconf;
            String pathxml = this.pathxml;
            
            //Read file conf
            File inputFile = new File(pathconf);
            InputStream is = new FileInputStream(inputFile);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
 
            //load the buffered file
            prop.load(br);
            String name = prop.getProperty("name");
                        
            //Read xml file to get the format
            FileReader reader = new FileReader(pathxml);            
            
            String newString;
            StringBuffer str = new StringBuffer();
            
            String lineSeparator = System.getProperty("line.separator");
        
            BufferedReader rb = new BufferedReader(reader);
            
            //read file.ini to HashMap
            Map<String, String> mapFromFile = getHashMapFromFile();
            
            //iterate over HashMap entries
            for(Map.Entry<String, String> entry : mapFromFile.entrySet()){
                
                System.out.println( entry.getKey() + " -> " + entry.getValue() );
                
                //replace values
                while ((newString = rb.readLine()) != null){
                    str.append(lineSeparator);
                    str.append(newString.replaceAll(entry.getKey(), entry.getValue()));         
                }
            }
                
            rb.close();
            
            String pathwriter = pathxml + name + ".scxml";
                        
            BufferedWriter bw = new BufferedWriter(new FileWriter(new File(pathwriter)));
            
            bw.write(str.toString());        
            //flush the stream
            bw.flush();      
            //close the stream
            bw.close();
                
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }     
        
        return result;
    }

so my .ini file is for example

Apple = red
Lemon = yellow

it print key and values correctly:

Apple -> red
Lemon -> yellow

but replace in the file only Apple with red and not the others key


Solution

  • The problem lays in your control flow order.

    By the time the first iteration in your for loop, which corresponds to the first entry Apple -> red, runs it would caused the BufferedReader rb to reach the end of stream, hence doing nothing for subsequent iterations.

    You have then either to reinitialize the BufferedReader for each iteration, or better, inverse the looping over your Map entries to be within the BufferedReader read loop:

    EDIT (following @David hints)

    You should can assign the resulting replaced value to the line replacement that will be appended to the result file at each line iteration:

    public String getPropValues() throws IOException {
    
        try {
    
            // ...
        
            BufferedReader rb = new BufferedReader(reader);
            
            //read file.ini to HashMap
            Map<String, String> mapFromFile = getHashMapFromFile();
    
            //replace values
            while ((newString = rb.readLine()) != null) {
                // iterate over HashMap entries
                for (Map.Entry<String, String> entry : mapFromFile.entrySet()) {
                    newString = newString.replace(entry.getKey(), entry.getValue());  
                }
                str.append(lineSeparator)
                    .append(newString);
            }
                
            rb.close();
            
            // ...
                
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }     
        
        return result;
    }