Advertisement
BullyATWiiplaza

File Operations

Sep 23rd, 2014
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7.  
  8. public class FileOperations
  9. {
  10.     public static void deleteDirectory(File directory)
  11.     {
  12.         File[] children = directory.listFiles();
  13.  
  14.         for (int i = 0; i < children.length; i++)
  15.         {
  16.             if (children[i].isFile())
  17.             {
  18.                 children[i].delete();
  19.             } else
  20.             {
  21.                 deleteDirectory(children[i]);
  22.                 children[i].delete();
  23.             }
  24.         }
  25.  
  26.         directory.delete();
  27.     }
  28.  
  29.     public static void copyDirectory(File sourceLocation, File targetLocation)
  30.             throws IOException
  31.     {
  32.         if (sourceLocation.isDirectory())
  33.         {
  34.             if (!targetLocation.exists())
  35.             {
  36.                 targetLocation.mkdir();
  37.             }
  38.  
  39.             File[] children = sourceLocation.listFiles();
  40.  
  41.             for (int i = 0; i < children.length; i++)
  42.             {
  43.                 copyDirectory(children[i],
  44.                         new File(targetLocation, children[i].getName()));
  45.             }
  46.         } else
  47.         {
  48.             copyFile(sourceLocation, targetLocation);
  49.         }
  50.     }
  51.  
  52.     private static void copyFile(File sourceLocation, File targetLocation)
  53.             throws IOException
  54.     {
  55.         InputStream inputStream = new FileInputStream(sourceLocation);
  56.         OutputStream outputStream = new FileOutputStream(targetLocation);
  57.  
  58.         byte[] buffer = new byte[1024];
  59.         int length;
  60.  
  61.         while ((length = inputStream.read(buffer)) > 0)
  62.         {
  63.             outputStream.write(buffer, 0, length);
  64.         }
  65.  
  66.         inputStream.close();
  67.         outputStream.close();
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement