commons io FileUtils.writeStringToFile

DaeYoung picture DaeYoung · May 23, 2014 · Viewed 15.6k times · Source

I have a program written in Java reading two properties files - source.properties and destination.properties and write key/value pair of each line from source to destination. I decided to use FileUtils.writeStringToFile method from apache commons io api instead of PrintWriter or FileWriter from java standard api. What I found is only last line in the source file is overwritten to the destination file.

contents of the source.properties
username=a
host=abc

contents of the destination.properties
host=abc

  static void writeToFile(Map<String,String> map, String pathToFile)    {                                 
    Iterator<Map.Entry<String,String>> itr = map.entrySet().iterator();
    File path = new File(pathToFile);
    while(itr.hasNext())    {
        Map.Entry<String,String> pairs = (Map.Entry<String,String>)itr.next();
        FileUtils.writeStringToFile(path,pairs.getKey() + "=" + pairs.getValue());
    }
}

map contains key/value pairs from the source file. When I debugged the program, I was able to see while loop go through two times and map contained all the correct data and the method from FileUtils called two times and wrote each line of data from the source file.

Can someone explain to me why I am getting aforementioned output?

[update]
I was able to achieve what I wanted in using PrintWriter.

Answer

tmarwen picture tmarwen · May 23, 2014

You have to use the FileUtils#writeStringToFile with a boolean argument set to true to tell the utils method that it should append the String to the end of file and not overwite it.

@Deprecated
public static void writeStringToFile(File file,
                            String data,
                            boolean append)
                          throws IOException

So you code should be as below:

static void writeToFile(Map<String,String> map, String pathToFile)
{                                 
  Iterator<Map.Entry<String,String>> itr = map.entrySet().iterator();
  File path = new File(pathToFile);
  while(itr.hasNext())    {
    Map.Entry<String,String> pairs = (Map.Entry<String,String>)itr.next();
    FileUtils.writeStringToFile(path,
      pairs.getKey() + "=" + pairs.getValue(), 
      true);// append rather than overwrite
  }
}

Sidenote: This method is deprecated and you should use the one with Charset specified in method signature.