How to copy file from one location to another location?

后端 未结 6 961
攒了一身酷
攒了一身酷 2020-11-28 23:02

I want to copy a file from one location to another location in Java. What is the best way to do this?


Here is what I have so far:

import java.i         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 23:32

    Use the New Java File classes in Java >=7.

    Create the below method and import the necessary libs.

    public static void copyFile( File from, File to ) throws IOException {
        Files.copy( from.toPath(), to.toPath() );
    } 
    

    Use the created method as below within main:

    File dirFrom = new File(fileFrom);
    File dirTo = new File(fileTo);
    
    try {
            copyFile(dirFrom, dirTo);
    } catch (IOException ex) {
            Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
    }
    

    NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.

    Credits - @Scott: Standard concise way to copy a file in Java?

提交回复
热议问题