Sunday, March 20, 2011

Delete File by Java

import java.io.*;

class isuru{
 public static void main(String args[]){
  if(args.length != 1){
   System.err.println("Usage: java Delete");
   System.exit(0);
  }try{
   delete(args[0]);
   System.out.println("Deleted successfully!");
  }catch(IllegalArgumentException e){
   System.err.println(e.getMessage());
  }
 }
 
 public static void delete(String fileName){
  File f = new File(fileName);
  if(!f.exists()) fail("Delete: no such file or Directory:"+fileName);
  if(!f.canWrite()) fail("Delete: write protected:"+fileName);
  
  if(f.isDirectory()){
   String[] files = f.list();
   if(files.length > 0){
    fail("Delete: directory not empty: "+fileName);
   }
  }
  
  boolean success = f.delete();
  
  if(!success) fail("Delete: deletion failed! ");
 }
 
 protected static void fail(String msg) throws IllegalArgumentException{
  throw new IllegalArgumentException(msg);
 }
}

1 comment:

  1. thanks! very good articles
    http://linuxbasiccommand.blogspot.com

    ReplyDelete