Wednesday, April 29, 2015

Working smarter, not harder

I'm currently interning at Loadmaster, an oil rig design company based in Houston. Yesterday I was tasked with writing a script to delete files in our scanned files directory that were over 45 days old.

Doesn't sound too complicated right? Well a quick google search revealed that many others have done similar projects.

Starting with a script from TechnicalKeeda as a base, I saved time by tweaking his script to my needs instead of starting from scratch. After adding a few printlns to readout more information, increasing the scan to target all file types in the directory, and changing the days required for deletion eligibility I had a working script in 15 minutes.

After that I wrote a simple batch file to run the .jar, set it up on our server's task scheduler and voilĂ . Here's my finished code, and an example of the readout.
.

/**
 *
 * deletes files in the scan directory
 */
import java.io.File;


public class ScanDelete {


  private String dirPath = "\\\\utility\\scans";

  public static void main(String[] args) {
    ScanDelete deleteFiles = new ScanDelete();
    deleteFiles.delete(45, "");
  }

  public void delete(long days, String fileExtension) {
 
    File folder = new File(dirPath);
 
    if (folder.exists()) {
   
      File[] listFiles = folder.listFiles();
   
      long eligibleForDeletion = System.currentTimeMillis()
        - (days * 24 * 60 * 60 * 1000L);
   
      for (File listFile : listFiles) {
        System.out.println("browsing...");    
        System.out.println("File Name: " + listFile.getName());
        System.out.println("Last modified: " + listFile.lastModified());
        System.out.println("Eligible for deletion: " + eligibleForDeletion);
        if (listFile.lastModified() < eligibleForDeletion) {
          System.out.println("Deleting File" );
          System.out.println("-----------------------------------" );
          listFile.delete();
        } else {
          System.out.println("File Spared" );
          System.out.println("-----------------------------------" );
        }
      }
    } else {
      System.out.println("Error: Folder Doesn't Exist!");
    }
  }

Here's the point: One of the most valuable skills you can learn as a programmer is resource management. Take advantage of the fact that there have been thousands before you trying to solve the same problems, and don't waste time writing small scripts that have already been written for you.

No comments:

Post a Comment