How to copy file from one location to another location?

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

    Using Stream

    private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }
    

    Using Channel

    private static void copyFileUsingChannel(File source, File dest) throws IOException {
        FileChannel sourceChannel = null;
        FileChannel destChannel = null;
        try {
            sourceChannel = new FileInputStream(source).getChannel();
            destChannel = new FileOutputStream(dest).getChannel();
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
           }finally{
               sourceChannel.close();
               destChannel.close();
           }
    }
    

    Using Apache Commons IO lib:

    private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
        FileUtils.copyFile(source, dest);
    }
    

    Using Java SE 7 Files class:

    private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
        Files.copy(source.toPath(), dest.toPath());
    }
    

    Or try Googles Guava :

    https://github.com/google/guava

    docs: https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html

    Compare time:

        File source = new File("/Users/sidikov/tmp/source.avi");
        File dest = new File("/Users/sidikov/tmp/dest.avi");
    
    
        //copy file conventional way using Stream
        long start = System.nanoTime();
        copyFileUsingStream(source, dest);
        System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
         
        //copy files using java.nio FileChannel
        source = new File("/Users/sidikov/tmp/sourceChannel.avi");
        dest = new File("/Users/sidikov/tmp/destChannel.avi");
        start = System.nanoTime();
        copyFileUsingChannel(source, dest);
        System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
         
        //copy files using apache commons io
        source = new File("/Users/sidikov/tmp/sourceApache.avi");
        dest = new File("/Users/sidikov/tmp/destApache.avi");
        start = System.nanoTime();
        copyFileUsingApacheCommonsIO(source, dest);
        System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));
         
        //using Java 7 Files class
        source = new File("/Users/sidikov/tmp/sourceJava7.avi");
        dest = new File("/Users/sidikov/tmp/destJava7.avi");
        start = System.nanoTime();
        copyFileUsingJava7Files(source, dest);
        System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));
    
    0 讨论(0)
  • 2020-11-28 23:08
      public static void copyFile(File oldLocation, File newLocation) throws IOException {
            if ( oldLocation.exists( )) {
                BufferedInputStream  reader = new BufferedInputStream( new FileInputStream(oldLocation) );
                BufferedOutputStream  writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
                try {
                    byte[]  buff = new byte[8192];
                    int numChars;
                    while ( (numChars = reader.read(  buff, 0, buff.length ) ) != -1) {
                        writer.write( buff, 0, numChars );
                    }
                } catch( IOException ex ) {
                    throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
                } finally {
                    try {
                        if ( reader != null ){                      
                            writer.close();
                            reader.close();
                        }
                    } catch( IOException ex ){
                        Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() ); 
                    }
                }
            } else {
                throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
            }
        }  
    
    0 讨论(0)
  • 2020-11-28 23:09

    You can use this (or any variant):

    Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
    

    Also, I'd recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.

    Since you're not sure how to temporarily store files, take a look at ArrayList:

    List<File> files = new ArrayList();
    files.add(foundFile);
    

    To move a List of files into a single directory:

    List<File> files = ...;
    String path = "C:/destination/";
    for(File file : files) {
        Files.copy(file.toPath(),
            (new File(path + file.getName())).toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    }
    
    0 讨论(0)
  • 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!!!!!!!!!!!!!!");
    
    
                }
    
    0 讨论(0)
  • 2020-11-28 23:30

    Files.exists()

    Files.createDirectory()

    Files.copy()

    Overwriting Existing Files: Files.move()

    Files.delete()

    Files.walkFileTree() enter link description here

    0 讨论(0)
  • 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?

    0 讨论(0)
提交回复
热议问题