Fastest way to copy files in Java

后端 未结 6 1035
萌比男神i
萌比男神i 2021-02-07 01:32

What ist the fastest way to copy a big number of files in Java. So far I have used file streams and nio. Overall streams seem to be faster than nio. What experiences did you mak

6条回答
  •  面向向阳花
    2021-02-07 01:36

    I would use:

    import java.io.*;
    import java.nio.channels.*;
    
    public class FileUtils{
        public static void copyFile(File in, File out) 
            throws IOException 
        {
            FileChannel inChannel = new
                FileInputStream(in).getChannel();
            FileChannel outChannel = new
                FileOutputStream(out).getChannel();
            try {
                inChannel.transferTo(0, inChannel.size(),
                        outChannel);
            } 
            catch (IOException e) {
                throw e;
            }
            finally {
                if (inChannel != null) inChannel.close();
                if (outChannel != null) outChannel.close();
            }
        }
    
        public static void main(String args[]) throws IOException{
            FileUtils.copyFile(new File(args[0]),new File(args[1]));
      }
    }
    

    If any of your files are bigger than 64M in Windows you might need to look at this: http://forums.sun.com/thread.jspa?threadID=439695&messageID=2917510

提交回复
热议问题