如何在java中备份文件?

问题描述 投票:1回答:3

实际上它只是制作text.txt文件的副本。我知道如何使用文件选择器来选择文件,但据我所知,这是真的。

我可以做这个:

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");
   }

}
java copy backup filechooser
3个回答
4
投票

Path对象非常适合复制文件, 尝试使用此代码复制文件,

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

0
投票

首先来看看Basic I/O,它解释了Input/OutputStreamsReaders以及Writers的基础知识,它们用于读取/写入从源到目标的数据字节。

如果您使用的是Java 7或更高版本,您还应该查看Copying a File or Directory,它是较新的FilesPaths API的一部分,您可以在File I/O (Featuring NIO.2)找到更多相关信息。


0
投票

如果必须备份整个文件夹,则可以使用此代码

public class BackUpFolder {

    public void copy(File sourceLocation, File targetLocation) throws IOException {
        if (sourceLocation.isDirectory()) {
            copyDirectory(sourceLocation, targetLocation);
        } else {
            copyFile(sourceLocation, targetLocation);
        }
    }

    private void copyDirectory(File source, File target) throws IOException {
        if (!target.exists()) {
            target.mkdir();
        }

        for (String f : source.list()) {
            copy(new File(source, f), new File(target, f));
        }
    }

    private void copyFile(File source, File target) throws IOException {
        try (
                InputStream in = new FileInputStream(source);
                OutputStream out = new FileOutputStream(target)) {
            byte[] buf = new byte[1024];
            int length;
            while ((length = in.read(buf)) > 0) {
                out.write(buf, 0, length);
            }
        }
    }

    public static void main(String[] args) {
        try {
            BackUpFolder backUpFolder = new BackUpFolder();
            String location = "./src/edu/abc/locationFiles/daofile"; //File path you are getting from file chooser
            String target = "./src"; //target place you want to patse
            File locFile = new File(location);
            File tarFile = new File(target);
            backUpFolder.copyDirectory(locFile, tarFile);
        } catch (IOException ex) {
            Logger.getLogger(BackUpFolder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.