Advertisement
LegarsStyler

Copy directory

Oct 30th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. public void copy(File sourceLocation, File targetLocation) throws IOException {
  2.     if (sourceLocation.isDirectory()) {
  3.         copyDirectory(sourceLocation, targetLocation);
  4.     } else {
  5.         copyFile(sourceLocation, targetLocation);
  6.     }
  7. }
  8.  
  9. private void copyDirectory(File source, File target) throws IOException {
  10.     if (!target.exists()) {
  11.         target.mkdir();
  12.     }
  13.  
  14.     for (String f : source.list()) {
  15.         copy(new File(source, f), new File(target, f));
  16.     }
  17. }
  18.  
  19. private void copyFile(File source, File target) throws IOException {        
  20.     try (
  21.             InputStream in = new FileInputStream(source);
  22.             OutputStream out = new FileOutputStream(target)
  23.     ) {
  24.         byte[] buf = new byte[1024];
  25.         int length;
  26.         while ((length = in.read(buf)) > 0) {
  27.             out.write(buf, 0, length);
  28.         }
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement