Couple of dayes back we got a requirement to replace an existing file or create a new if it does not exist. I will be using Go-lang to explain different solutions with pros and cons.

Using Built-in ioutil Function

This is a quickest solution to use built-in ioutil function from the language.
  • Read file constant using ioutil.ReadFile(src)
  • Write file content using ioutil.WriteFile(dest, input, 0644)
Things to Remember
This is the fastest approach to copy file content from one to another. Only issue will be memory utilization because ioutil.ReadFile(source) loads all the file content in a byte array, if our file size grows beyond a limit it can crash program.

Using Built-in ioutil Function

Another approach is to open both the files and copy these using built-in io functions from the language.
  • Open new file for reading (In Read Mode) using os.Open(src).
  • Then open existing file for writing, so that it can create a file if it does no exist (In Read/Write Mode, and don't truncate existing file.) using os.OpenFile(dest, os.O_RDWR|os.O_CREATE, 0644).
  • At last make use of io.Copy(destination, source) function available in the library to copy content from one file to another.
Things to Remember
Only issue with this approach is if existing file bigger (has more bytes than) the new file there will be chances of file curreption.

Create Using built-in io Functions

Third and right approach is to open new the file and create another one and copy these using built-in io functions from the language.
  • Open new file for reading (In Read Mode) using os.Open(src)
  • Create a new file for copy instead of opening existing file for writing, this takes care of new file creation and truncate if file already exist os.Create(dest)
  • Use io.Copy(destination, source) function available in the library to copy content from one file to another
Things to Remember
io.Copy(destination, source) internally uses buffer to copy files, so there will not be any memory issue. os.Create(dest) creates a new file or truncate if it exists, so there wont be any issue related to file corruption.