使用JavaEclipse将文件从一个文件夹复制到另一个文件夹(使用错误处理程序)

使用JavaEclipse将文件从一个文件夹复制到另一个文件夹(使用错误处理程序),java,automation,Java,Automation,我正试图使用Files.copy()将一个文件从一个文件夹复制到另一个文件夹,我成功地做到了这一点 但是,我希望代码更加灵活,可以有一条消息说“文件移动不成功!”,“文件已存在”(如果该文件已存在于该文件夹中) 代码: package practice; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public c

我正试图使用
Files.copy()
将一个文件从一个文件夹复制到另一个文件夹,我成功地做到了这一点

但是,我希望代码更加灵活,可以有一条消息说“文件移动不成功!”“文件已存在”(如果该文件已存在于该文件夹中)

代码:

package practice;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


public class test2 {

    public static void main(String[] args) {

        Path source = Paths.get("C:\\Downloads\\fileinput\\fileinput.csv");
        Path destination = Paths.get("C:\\Downloads\\landingzone\\fileinput.csv");
        System.out.println("File is moved successful!");

        try {
            Files.copy(source, destination);

        } catch (IOException e) {

            System.out.println("File move unsuccessful!");
            e.printStackTrace();
        }
    }
}

处理错误的理想方法是捕获该过程中发生的异常。我相信只要你再努力一点,你就能做到

下面是一个简单的
try/catch
代码块,您可以使用它捕获异常,并查看操作是否成功

import java.io.IOException;
import java.nio.file.*;

public class Program {
    public static void main(String[] args) {    
        //These files do not exist in our example.
        FileSystem system = FileSystems.getDefault();
        Path original = system.getPath("C:\\programs\\mystery.txt");
        Path target = system.getPath("C:\\programs\\mystery-2.txt");

        try {
            //Throws an exception on error
            Files.copy(original, target);
        } catch (IOException ex) { 
            System.out.println("ERROR");
        }
    }
}

此外,对于
Files.copy()
方法,您应该查看java文档。

在启动文件复制过程之前,您需要检查目标位置是否存在文件

public static void main( String[] args ) {

        Path source = Paths.get( "C:\\Downloads\\fileinput\\fileinput.csv" );
        Path destination = Paths.get( "C:\\Downloads\\landingzone\\fileinput.csv" );

        try {

            if ( Files.exists( destination ) ) { // check file is exists at destination

                System.out.println( "File exists already." );
            } else {

                Files.copy( source, destination );

                System.out.println( "File copied successfully" );
            }


        } catch ( IOException e ) {

            System.out.println( "File move unsuccessful!" );
            e.printStackTrace();
        }
    }