Fastest way to copy files in Java

后端 未结 6 1028
萌比男神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:39

    Its depend of files(bigger files), for me is fastest way this one with buffered stream

     public void copyFile(File inFileStr, File outFileStr) throws IOException {
    
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inFileStr)); 
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFileStr))) {
    
            byte[] buffer = new byte[1024 * 1024];
            int read = 0;
            while ((read = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, read);
            }
    
            bis.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    
    }
    

提交回复
热议问题