Tuesday, February 6, 2024

Backing Up A File

 Backing up a file in Java can be fairly simple and straight forward. Let's think about it for a second. You have a file.

  1. You want to be able to store a copy of that file somewhere on your file system.
  2. You either want to keep the original or delete the original.
  3. The format of the filename must be unique, so it doesn't collide with other backed up files.
There are just a few considerations to think about. Here's a solution I came up with in Java:


import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.File;
import java.util.Date;
import java.text.SimpleDateFormat;

public class Backup {

    public static void main(String[] args) {
        if (args.length == 1) {
            File file = new File(args[0]);

            if (file.exists()) {
                try {
                    File dir = new File("archive");
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    Date date = new Date();
                    SimpleDateFormat dt = new SimpleDateFormat("'.'yyyy-MM-dd-HH-mm-ss");
                    Path source = Paths.get(args[0]);
                    Path target = Paths.get(dir.getName(), file.getName() + dt.format(date));

                    System.out.println("Backing up file: " + source + " --> " + target);

                    Files.copy(source, target);
                    file.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.err.println("The file you specified '" + file.getName() + "' doesn't exist.");
            }
        }
    }
}

As you can see I chose to delete the file at the end of the process. But let's take a look at what this does:

  1. We make sure at least one filenamne is passed in and if it exists we continue.
  2. We create a home for the archived file, in this example we call it archive.
  3. We create a date and format it.
  4. We set a source and a target and output that we are copying the source to the target.
  5. Using Files.copy we do the actual backup.
  6. Then we delete the file at the end of the process.

That's all there is to it. I'm sure there could be a way to refactor this so it's better somehow. I'll have to look into it.

No comments:

Post a Comment

Ever feel like no one is listening?

 Ever have that feeling that no one is listening to you? Yeah, that feeling. It can be a strong feeling to have, a hurtful feeling also. The...