Search code examples
javajsonfilewriteris-empty

Java FileWriter not writing to file


I'm creating an app which requires to write a file for every user (in JSON format).

The app successfully creates the file, But it's empty. In the code I added a finer output to see how the converted JSON String looks like, and I noticed that it's complete (it contains everything, so the conversion is ok). But the string isn't present in the file.

//create a new FileWriter C:/.../42.guser
        FileWriter writer = null;

        //for every User
        for(int i=0; i<users.size(); i++) {

            try {
                File f = new File(Users.usersDir.getPath()+"/"+i+".guser");

                //Create new file
                f.createNewFile();

                writer = new FileWriter(f);

                //convert to json and write to file. Here we get the object with KEY = keys[i].
                String stringedUsr = gson.toJson(users.get(keys[i]));

                logger.finer("Converted user: \""+stringedUsr+"\""); //Output seems ok

                //Write (NOT WORKING)
                writer.write(stringedUsr);

                logger.fine("Wrote updated user \""+keys[i]+"\" to file "+f.getCanonicalPath());

            } catch (IOException e) {
                FAILS++;
                e.printStackTrace();
            }

        }
        //End of for

What am I doing wrong?

Note: i gave to the app all the necessary Permissions. No AccessControlExceptions


Solution

  • First of all think about closing your writer. When closing, it should flush() your data first (as mentioned in the doc here)

    You can also flush() manually.