How to copy file from one location to another location?

后端 未结 6 945
攒了一身酷
攒了一身酷 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:28

    Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original). Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.

     public static void main(String[] args) throws IOException {
                    String destFolderPath = "D:/TestFile/abc";
                    String fileName = "pqr.xlsx";
                    String sourceFilePath= "D:/TestFile/xyz.xlsx";
                    File f = new File(destFolderPath);
                    if(f.mkdir()){
                        System.out.println("Directory created!!!!");
                    }
                    else {
                        System.out.println("Directory Exists!!!!");
                    }
                    f= new File(destFolderPath,fileName);
                    if(f.createNewFile())   {
    
                        System.out.println("File Created!!!!");
                    }   else {
                        System.out.println("File exists!!!!");
                    }
    
                    Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
                    System.out.println("Copy done!!!!!!!!!!!!!!");
    
    
                }
    

提交回复
热议问题