Java Fast File Copy using NIO


/ Published in: Java
Save to your folder(s)

Java Fast File Copy using NIO


Copy this code and paste it in your HTML
  1. public static void fileCopy( File in, File out )
  2. throws IOException
  3. {
  4. FileChannel inChannel = new FileInputStream( in ).getChannel();
  5. FileChannel outChannel = new FileOutputStream( out ).getChannel();
  6. try
  7. {
  8. // inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows
  9.  
  10. // magic number for Windows, 64Mb - 32Kb)
  11. int maxCount = (64 * 1024 * 1024) - (32 * 1024);
  12. long size = inChannel.size();
  13. long position = 0;
  14. while ( position < size )
  15. {
  16. position += inChannel.transferTo( position, maxCount, outChannel );
  17. }
  18. }
  19. finally
  20. {
  21. if ( inChannel != null )
  22. {
  23. inChannel.close();
  24. }
  25. if ( outChannel != null )
  26. {
  27. outChannel.close();
  28. }
  29. }
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.