[英]Java: Safe way to copy/move files from one directory to another
We have a system where we are dealing with file operations, and in my case i would have to copy or move file(s) from one directory to another. 我们有一个处理文件操作的系统,以我为例,我将不得不将文件从一个目录复制或移动到另一个目录。 Could anybody let me know a safe way to do this? 有人能让我知道安全的方法吗? For instance: lets say during the copy or move execution, if the system reboots, how do i ensure my operation executes gracefully. 例如:假设在复制或移动执行期间,如果系统重新启动,我如何确保我的操作正常执行。 An example snippet would be very helpful. 一个示例代码片段将非常有帮助。
You can use this way: 您可以使用这种方式:
File fileFrom= new File("/FileDirectory");
Path FROM = Paths.get(fileFrom.getPath());
File fileTo= new File("/FileDirectory");
Path TO = Paths.get(fileTo.getPath());
//sobreescribir el fichero de destino, si existe, y copiar los atributos, incluyendo los permisos rwx
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
try {
Files.copy(FROM, TO, options);
} catch (FileNotFoundException ex) {
System.out.println("Error1: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("Error2: " + ex.getMessage());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.