Search code examples
javahashmapbufferedwriterwritetofile

Iterating over HashMap then writing integers into file


I have been trying for quite some time to Iterate over a HashMap and then write the keys from the HashMap into a file.

This is what I have been doing

HashMap<String,Integer> myHashMap = new Hashmap<String,Integer>();

 myHashMap.put(aString,1)
 myHashMap.put(bString,2)
 myHashMap.put(cString,3)
//..

private void doStuff(){
try {
        // Create new file
        String path = "myCreatedTxt.txt";
        File file = new File(path);

        // If file doesn't exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

        for (Map.Entry<String,Integer> dic : myHashMap.entrySet())
        {
            System.out.println(dic.getKey() + "/" + dic.getValue());
            bw.write(dic.getKey()+"");
        }

        // Close connection
        bw.close();
    } catch (IOException x) {
        System.out.println(x);
    }
}

But when doStuff() is called, although a file named myCreatedTxT is created, it's empty.

I am expecting to get a result that would look something like:

---inside myCreatedFile.txt--- 1 11 4 2 5 6 7

In an way I tried before I could only get a single key written on the file but that wasn't enough, as I need every key.

I would like to hear some advice or explanations

Thanks.

P.S of course, doStuff() is called somewhere in the program in a finally{} block.


Solution

  • I created Writer class for this example :

    public class Writer {
        private Map<String, Integer> myHashMap;
    
        public Writer() {
            myHashMap = new HashMap<>();
    
            myHashMap.put("a", 1);
            myHashMap.put("b", 2);
            myHashMap.put("c", 3);
        }
    
    
        public void doStuff() {
            try {
                // Create new file
                final String path = "myCreatedTxt.txt";
                File file = new File(path);
    
                // If file doesn't exists, then create it
                if (!file.exists()) {
                    file.createNewFile();
                }
    
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
    
    
                myHashMap.entrySet().forEach(x -> {
                    try {
                        bw.write(x.getKey() + " ");
                    } catch (IOException e) {
                        System.out.println("error accord");
                    }
                });
    
                // Close connection
                bw.close();
            } catch (IOException x) {
                System.out.println(x);
            }
        }
    }
    

    And invoked it from my main class :

    public class Main {
            public static void main(String[] args) {
               Writer writer = new Writer();
    
               writer.doStuff();
            }
    }
    

    My output file looks exactly like that :

    a b c
    

    That should do the work