Search code examples
javacopybackupfilechooser

how to backup file in java?


In reality its just making a copy of a text.txt file. I know how to use file chooser to choose the file but that is as far as my knowledge really goes.

I can do this:

public BasicFile()
{
   JFileChooser choose = new JFileChooser(".");
   int status = choose.showOpenDialog(null);

   try
   {
        if (status != JFileChooser.APPROVE_OPTION) throw new IOException();

        f = choose.getSelectedFile();

        if (!f.exists()) throw new FileNotFoundException();
   }
   catch(FileNotFoundException e)
   {
        display(1, e.toString(), "File not found ....");
   }
   catch(IOException e)
   {
        display(1, e.toString(),  "Approve option was not selected");
   }

}

Solution

  • Path object is perfect for copying files,
    Try this code to copy a file,

    Path source = Paths.get("c:\\blabla.txt");
        Path target = Paths.get("c:\\blabla2.txt");
        try {
            Files.copy(source, target);
        } catch (IOException e1) {
            e1.printStackTrace();
        }