File deletion in java(amma12)

i am trying to delete files in history folder,which is in windows folder of my system.but its not able to delete them.i am successfull in delting files from a folder made by me(for eg.c:\ab) which is having html files.the same i applied for history folder,but was'nt successfull.please tell me hoe to do it,and also tell what is the extension of
internet shortcut files.i need it,please have a look at my program.
import java.io.*;
import java.awt.*;
public class del
static File f2,f3;
static int i=0;
public static void main(String s[])
Runtime r=Runtime.getRuntime();
File f=new File("c:/Windows/History");
FilenameFilter only1=new only("html");
String ss[]=f.list(only1);
for(;i<ss.length;i++)
f2=new File(f,ss);
boolean b=f2.delete();
System.out.print(b);
class only implements FilenameFilter
String ext;
public only(String ext)
this.ext="."+ext;
public boolean accept(File dir,String name)
return name.endsWith(ext);

File f = new File("c:\\Windows\\History");
try that

Similar Messages

  • Java.io.File.delete worked in 1.1, 1.2, 1.3 & 1.4, but not in 5.0

    I have a logging utility I wrote originally in Java 1.0. A nightly housekeeping task runs which creates a ZIP file for the previous days log, then deletes the .log file. If I run this software with Java 5.0, the File.delete fails and the .LOG file remains on the disk. No exceptions are thrown. delete just returns false.
    Any ideas?

    to find a bug this basic! Each day I switch to a new log file, leaving the previous days file. I was never closing the old PrintStream... Jees... How embarrassing.

  • Problem in deleting Zip files unzipped using java.util.zip

    I have a static methos for unzipping a zip file. after unzipping the file when i am trying to delete that file using File.delete()its not getting deleted. but when methods like exist(). canRead(), canWrite() methods are returning true what can be the possible problem ? i had closed all the streams after unzipping operation Please go through the following code.
    public static boolean unzipZipFile(String dir_name, String zipFileName) {
    try {
    ZipFile zip = new ZipFile(zipFileName);
    Enumeration entries = zip.entries();
    while (entries.hasMoreElements()) {
    ZipEntry entry = (ZipEntry) entries.nextElement();
    // got all the zip entries here
    // now has to process all the files
    // first all directories
    // then all the files
    if (entry.isDirectory()) {
    // now the directories are created
    File buf=new File(dir_name,entry.getName());
    buf.mkdirs();
    continue;
    }// now got the dirs so process the files
    entries = zip.entries();
    while(entries.hasMoreElements()) {
    // now to process the files
    ZipEntry entry = (ZipEntry) entries.nextElement();
    if (!entry.isDirectory()){
    File buf=new File(dir_name,entry.getName());
    copyInputStream(
    zip.getInputStream(entry),
    new BufferedOutputStream(
    new FileOutputStream(buf)));}
    } catch (IOException e) {
    e.printStackTrace();
    return false;
    return true;
    now i am trying to call this method to unzip a zip file
    public static void main (String arg[]){
    unzipZipFile("C:/temp","C:/tmp.zip");
    java.io.File filer = new File("C:/tmp.zip");
    System.out.println (filer.canRead());
    System.out.println (filer.canWrite());
    System.out.println (filer.delete());
    Please tell me where my program is going wrong ?

    Thanks .. the problem is solved... i was not closing the Zip file .. rather i was trying to close all the other streams that i used for IO operaion ... thanks a lot

  • Failed to delete a file in MS Vista using java.io.File.delete()

    while trying to delete a file using java.io.File.delete(), it returns true but the file lies intact.
    i'm sure there is no handle or stream open on the file..
    the same code is running fine in XP..
    if anyone can help me.. thanks

    thanks all..
    the problem is diagnosed further..
    MS Vista does not let a user program to delete any file from 'windows' or 'program files' directories..
    Even when the file is deleted manually thru explorer a confirmation is taken from the administrator.. even when he is logged in..
    i for now have opted to install and use my program in Vista outside 'program files' directory...
    more clarification welcome..

  • Alternative to File.delete() and deleteOnExit()

    Is there any GOOD way to delete physical files from a Java app running under Windows besides the File object's incredibly lame and emasculated delete() and deleteOnExit() methods?
    Despite my best efforts, I have yet to find ANY circumstances under which calling File.delete() will actually delete a file under Windows XP... It's as though the mere act of a running Java application becoming AWARE that a file exists is enough to make the JVM lock the file so nothing else can touch it (including the running app itself).
    Is there perhaps some alternate JNI-based alternative that treats deletions as more than polite suggestions that a file be considered for future removal, and PERSONALLY sees to it that the underlying OS makes an immediate and determined effort to physically delete the file IMMEDIATELY?

    The File object referenced above is used to open a FileInputStream, which is subsequently closed prior to calling the File object's delete() method.
    From what I've read about this problem over the past few days, it arises because Sun didn't follow their own best practices and left releasing the file lock to the Stream's finalize() method (or otherwise left some critical prerequisite to the lock's release to a garbage collection run)... which, as we all know, is something you should never do when you're DEPENDING upon having something executed because there's NO guarantee it will run in a timely manner, or even run at all (if, say, the application throws an Exception).
    Apparently, the problem arises something like this:
    A running Java app creates a File object and does something that requires doing actual I/O upon it, like opening an input/output stream.
    The JVM asks its abstraction layer to ask Windows to open the file. A delegate is dispatched to contact win32 and request a file lock. Windows creates a file lock in the thread's name, and gives the delegate the good news.
    The running app does its stream I/O.
    The running app closes the stream, and nullifies the object's reference just to be safe.
    Unfortunately, the JVM has other plans in mind. It throws the old Stream object into the garbage collector's work heap, then forgets it ever existed without bothering to stick around and personally make sure the file lock is released RIGHT AWAY.
    The running app continues... it's done with the file and has no further use for it, so it calls the File object's delete() method as its final act before nullifying the File object itself.
    The JVM dispatches another delegate to ask Windows to delete the file. Unfortunately, windows notices that the JVM still holds a lock on the file and tartly sends it home empty-handed, with instructions to tell its parent to make up its mind what it wants to do with the file. The delegate meekly reports failure, and the message is passed back to the running app without further action.
    What SHOULD happen:
    Calling Stream.close() should cause a delegate to be IMMEDIATELY dispatched to notify Windows that the lock should be released.
    OR, if Sun doesn't want to do that for performance reasons, then the JVM should double-check to make sure that the failure wasn't its own fault -- forcing an IMMEDIATE sweep through the garbage collector to return any queued-for-release file locks (possibly after taking a side trip to verify that the file still physically exists), followed by a second deletion attempt once it's certain that windows has responded to its request to release the lock.
    Calling System.gc() before calling File.delete() seems to work for now... but it's a really bad kludge that Sun needs to address since there's technically no guarantee that the garbage collector will actually run and release the lock.
    IMHO, this is an outright shameful bug. Sun can make all the lame excuses it wants to make about enforcing platform abstraction, but the fact is... anyone who calls File.delete() after personally making sure they've cleaned up after themselves by closing their streams has every reasonable expectation that the file will, in fact, be physically deleted unless some OTHER app or thread has acquired a secondary lock in the meantime. The buck has to stop somewhere. File deletion is one of those unglamorous tasks that nobody really thinks about until it doesn't work... and when it fails, it comes as a really rude surprise. If Sun can't alter the behavior of File.delete() for legacy reasons, then they should add an alternate method, like "File.deleteNow() throws RuntimeException" that guarantees the following behavior:
    "The JVM asks the host operating system to delete the file. If the OS refuses, the JVM tries to figure out why, and whether the failure might be its own fault. If it has reason to believe it's its own fault, it will force an immediate garbage collection run to clean up any outstanding mess, then ask the host OS to delete the file again. If it succeeds, the method returns true. If it fails, a RuntimeException (or subclass that actually lets the caller figure out why it failed) gets thrown."
    The key point is that File.delete() must NEVER fail unless some OTHER app, process, or thread that's completely unrelated to the one that locked the file and now wants it deleted has acquired a lock on the file in the meantime. I think just about everyone will agree that the current behavior of File.delete() under win32 absolutely violates the implicit contract that developers reasonably expect of a function to delete a file.
    Just to give one concrete example of a scenario where File.deleteOnExit() isn't feasible... suppose you have some emergency maintenance task that needs to be launched (with manually-supplied arguments) every few months when Something Bad happens... usually at night or over a weekend. To make life easy, the emergency app is implemented as a Servlet (so the notified individual can quickly and easily fix it in 3 minutes with his PalmOS phone and browser). The problem is, deleteOnExit() won't do much good when called from a Servlet, because the JVM running Tomcat hosting the Servlet is almost guaranteed to run for months without actually exiting... and when it finally DOES exit, it probably WON'T be graceful or intentional...

  • File.delete() - is there a way to send to Recycle Bin?

    I'm using the file.delete() command currently - is there a way, since all my users are on Windows, to Recycle the files instead?

    Wikipedia 'recycle bin' seems to indicate that the location may vary from
    OS to OS and from file system to file system.
    There are API's for it though.
    [http://www.codeproject.com/KB/shell/recyclebin.aspx] explains how to do it programmatically.
    You would have to write some JNI/JNA/Runtime.exec() code to bridge between Java and native.
    Edit: If you can find a command line utility that you can Runtime.exec(), good for you!
    I could not find any, but i did not search too much.
    Edit: Found some C++ code for such an utility:[http://msdn.microsoft.com/en-us/magazine/bb985590.aspx]
    Edited by: baftos on Aug 4, 2008 4:45 PM

  • Temporary files in a Java applet

    Hi to everybody.
    I am developing a Java applet that downloads ZIP files through HTTP, extract the content of these ZIP archives to a temporary folder, than uses the extracted files.
    When the applet is closed (browser closed or change of page in the browser), I would like to delete all the files and directories that have been created during the ZIP extraction.
    I've overridden the "destroy()" method, and I added the code to delete temp files in this method: this code recursively deletes all files and directories that are found under a given "root" directory.
    The entire procedure works fine when the browser unloads the applet since a new page address has been entered in the browser's address bar (i.e., request to load a new web page).
    On the other hand, there are problems when I simply close the browser (Internet Explorer): only some of the temporary files are deleted. It looks like the destroy() method is terminated before it comes to completion. I've also verified this, by trying to create a new file (named "Start.txt") at the beginning of the destroy() method (before the temp files deletion code), and another file (named "End.txt") at the end of the destroy() method (after the temp files deletion code): only the first file ("Start.txt") is created, thus confirming that the destroy() method is terminated before completion.
    Do you see some solution to my problem?
    I've also tried to use the deleteOnExit() method, by calling it immediately after each extracted file has been created, but this approach doesn't seem to work at all: perhaps IE does not terminate the JVM correctly...
    Any suggestion would be greatly appreciated.
    Thank you and best regards,
    Marco.

    Thanks a lot for your suggestion.
    I've tried to move the temp files deletion code in the stop() method, but nothing changes: everything works fine on web page change, but when I simply close the browser the stop() method is terminated before completion (hence, only part of the temp files are actually deleted).
    Any suggestion would be greatly appreciated.
    Regards,
    Marco.

  • File delete

    hi
    i want to delete files in a directory,
    i tried code like this but that is not usefull,the folder is still exsit there
    File dwnldDir = new File(project.GetLeft.GlobalConstants.MAIN_DOWNLOAD_DIRECTORY, dwnldID);
    //this will return name directory
              File[] innerFiles = dwnldDir.listFiles();
              for(int i=0; i < innerFiles.length; i++)
                   innerFiles.delete();
              }//end for
    then i tried this too,
    boolean success = (new File("innerFiles[i]")).delete();
    if (!success) {   
    System.out.println("file not deleted");
    but it shows "file not deleted "for every file.
    is there any problem with file permission,
    who can i change file permission in java.
    i created the directory and file by dowmloaded java class"MD5".
    when i check the permission it shows read only;
    plz help me
    thank u
    shilja

    Hi,
    As you have mentioned .... you have read only access ... you can read it but you can't delete it.
    It depend on which operating system you are ....
    on unix systems you can use "chmod +w <file_name> " this will again depend if you have permissions.
    on windows you can right click and check for properties ... there is check box <read only> you can deselect it.
    Hope this will work

  • Trying to delete file from trash but get this: The operation can't be completed because the item "File name" is in use. All other files delete except this one. Please help

    Trying to delete file from trash but get this: The operation can’t be completed because the item “File name” is in use. All other files delete except this one. Please help

    Maybe some help here:
    http://osxdaily.com/2012/07/19/force-empty-trash-in-mac-os-x-when-file-is-locked -or-in-use//

  • How to read the contents of XML file from my java code

    All,
    I created an rtf report for one of my EBS reports. Now I want to email this report to several people. Using Tim's blog I implemented the email part. I am sending emails to myself based on the USERID logic.
    However I want to email to different people other then me. My email addresses are in the XML file.
    From the java program which sends the email, how can I read the fields from XML file. If any one has done this, Please point me to the right examples.
    Please let me know if there are any exmaples/BLOG's which explain how to do this(basically read the contents of XML file in the Java program).
    Thank You,
    Padma

    Ike,
    Do you have a sample. I am searched so much in this forum for samples. I looked on SAX Parser. I did not find any samples.
    Please help me.
    Thank you for your posting.
    Padma.

  • Help needed  while exporting crystal reports to HTML file format using java

    Help needed  while exporting crystal reports to HTML file format using java api(not using crystalviewer).i want to download the
    html file of the report
    thanks

    the ReportExportFormat class does not have HTML format, it has got to be XML. Export to HTML is available from CR Designer only.
    Edited by: Aasavari Bhave on Jan 24, 2012 11:37 AM

  • HT2674 I have an iMac purchased in May 2011.  OSX Lion 10.7.3.  I deleted backup file from the external hard drive. Now, the trash can will not empty some of the files deleted.  File folder: "Core Services" contains a locked file: "boot.efi".  It will not

    I have an iMac purchased in May 2011.  OSX Lion 10.7.3.  I deleted backup file from the external hard drive which operates from Time Machine.
    Now, the trash can will not empty some of the files deleted from the backup harddrive.
    The trash contains-- File folder: "Core Services" which contains a locked file: "boot.efi". 
    It will not delete.
    How do I get the trash can empty of these files?

    Yes, the Old Master file has a folder for each year where I find all photos from that specific year. I am attaching a screen shot of the file.
    In the meantime i have managed to download all photos (it did not download any video files though in mpg, avi, 3gp, m4v,mp4 and mov format) to a new iphoto library. Unfortunately the photos are quite mixed and often doubled up. I ma considering to purchase iphoto library which checks all duplicates in iphoto. this will save me a lot of time. What do you think?

  • File.delete() and File.deleteOnExit() doesn't work consistently..

    I am seeing some odd behavior with trying to delete files that were opened. Usually just doing new File("file.txt").delete() would work. However, in this case, I have created an input stream to the file, read it in, saved it to another location (copied it), and now I am trying to delete it.
    The odd thing is, in my simple application, the user can work with one file at a time, but I move "processed" files to a lower pane in a swing app. When they exit it, it then archives all the files in that lower pane. Usually every file but the last one opened deletes. However, I have seen odd behavior where by some files don't delete, sometimes all of them wont delete. I tried the deleteOnExit() call which to me should be done by the JVM after it has released all objects such that they don't matter and the JVM ignores any object refs and directly makes a call (through JNI perhaps) to the underlying OS to delete the file. This doesn't work either.
    I am at a loss as to why sometimes some files delete, and other times they don't. In my processing code, I always close the input stream and set its variable to null. So I am not sure how it is possible a reference could still be held to the object representing the file on disk.

    and then, in the other class
      public int cdplayerINIToMMCD(File aDatabase, String thePassword) throws IllegalArgumentException {
         /*---------DATA---------*/
         String dbLogin, dbPassword;
         JFileChooser fc;
         INIFileFilter ff;
         int dialogReturnVal;
         String nameChosen;
         File INIFile;
         ProgressMonitor progressMonitor;
         BufferedReader inFileStream;
         String oneLine;
         int totalLines = 0;
         int linesParsed = 0;
         boolean openDBResult;
         int hasPassword;
         if ((aDatabase == null) || (!aDatabase.exists()) ||
            (FileManagement.verifyMMCD(aDatabase) == FileManagement.VERIFY_FAILED)) {
            throw new IllegalArgumentException();       
         else { 
            currentDB = aDatabase;
            if(thePassword == null) {
              dbPassword = "";
            else { dbPassword = thePassword; }
            dbLogin = dbPassword; //For MSAccess dbLogin == dbPassword
         //Ask the user for the cdplayer.ini file.
         //Create a file chooser
         if (System.getProperty("os.name").indexOf("Windows") > -1) {
            fc = new JFileChooser("C:\\Windows");
         else {
            fc = new JFileChooser();     
         fc.setMultiSelectionEnabled(false);
         fc.setDragEnabled(false);
         //Create a new FileFilter
         ff = new INIFileFilter();
         //Add this filter to our File chooser.
         fc.addChoosableFileFilter(ff);
         fc.setFileFilter(ff);
         //Ask the user to locate it.
         do {
            dialogReturnVal = fc.showOpenDialog(mainFrame);
            if (dialogReturnVal == JFileChooser.APPROVE_OPTION) {
               nameChosen = fc.getSelectedFile().getAbsolutePath();
               if(nameChosen.toLowerCase().endsWith(INIFileFilter.FILE_TYPE)) { INIFile=new File(nameChosen); }
               else { INIFile = new File(nameChosen+INIFileFilter.FILE_TYPE); }
               if (!INIFile.exists()) {
                  continue; //If the name specified does not exist, ask again.
               else { break; }
            else { //User clicked cancel in the open dialog.
               //Ignore what we've done so far.
               return(IMPORT_ABORTED);
         } while(true); //Keep asking until cancelled or a valid file is specified.
         //Determine how many lines will be parsed.
         try {
           //Open the INI for counting
           inFileStream = new BufferedReader(new InputStreamReader(new FileInputStream(INIFile)));
           while ((inFileStream.readLine()) != null) {
               totalLines++;
           //Close the INI file.
           inFileStream.close();
         } catch (IOException ex) { return(IMPORT_FAILED); }
         //Make a progress monitor that will show progress while importing.
         progressMonitor = new ProgressMonitor(mainFrame, "Importing file","", 0, totalLines);
         progressMonitor.setProgress(0);
         progressMonitor.setMillisToPopup(100);
         progressMonitor.setMillisToDecideToPopup(1);
         //Make our DatabaseHandler to insert results to the database.
         dbh = new DatabaseHandler();
         //Open the database connection.
         do {
           try {
              openDBResult = dbh.openDBConnection(currentDB, dbLogin, dbPassword);
           } catch(JDBCException ex) { return(IMPORT_JDBC_ERROR); } //OUCH! can't write anything.
             catch(SQLException ex) {
                 openDBResult = DatabaseHandler.OPNCN_FAILED;
                 //Can not open the database. Is it password protected?
                 hasPassword = JOptionPane.showConfirmDialog(mainFrame, "Could not open the database. "+
                                                "The password is wrong or you have not specified it.\n"+
                           "Do you want to enter one now?", "New password?", JOptionPane.YES_NO_OPTION);
                if (hasPassword == MMCDCatalog.DLG_OPTN_YES) {
                   dbPassword = JOptionPane.showInputDialog(mainFrame, "Please enter your "+
                                                              "password for the DataBase:");
                    dbLogin = dbPassword; //For MSAccess, login == password                                                    
                //If the password wasn't the problem, then we can't help it.
                else { return(IMPORT_FAILED); }
         } while(openDBResult != DatabaseHandler.OPNCN_OK); //If it is OK, no exception thrown.
         //Import the ini file
         try {
            //Open the INI file for parsing.
            inFileStream = new BufferedReader(new InputStreamReader(new FileInputStream(INIFile)));
            //Read and parse the INI file. Save entries once parsed.
            while ((oneLine = inFileStream.readLine()) != null) {
               parseLine(oneLine);
               linesParsed++;
               progressMonitor.setNote("Entries imported so far: "+entriesImported);
               progressMonitor.setProgress(linesParsed);
               if ((progressMonitor.isCanceled()) || (linesParsed == progressMonitor.getMaximum())) {
                  progressMonitor.close();
                  break;
            //Close the INI file.
            inFileStream.close();
         } catch (IOException ex) {
              //Make absolutely sure the progressMonitor has disappeared
                progressMonitor.close();
                if (dbh.closeDBConnection() != DatabaseHandler.CLSCN_OK) {
                 JOptionPane.showMessageDialog(mainFrame, "Error while reading the INI file.\n"+
                    "Error while attempting to close the database", "Error", JOptionPane.INFORMATION_MESSAGE);
              else {
                 JOptionPane.showMessageDialog(mainFrame, "Error while reading the INI file.",
                                                    "Error", JOptionPane.INFORMATION_MESSAGE);     
                return(IMPORT_FAILED);
         //Make absolutely sure the progressMonitor has disappeared
         progressMonitor.close();
         //Close the database connection
         if (dbh.closeDBConnection() != DatabaseHandler.CLSCN_OK) {
            JOptionPane.showMessageDialog(mainFrame, "Error while closing the database after import.",
                                          "Error", JOptionPane.INFORMATION_MESSAGE);
         //Did the user cancel?
         if (totalLines != linesParsed) {
            return(IMPORT_ABORTED);     
         //Success!
         //Everything ok. Return the number of entries imported.
         return(entriesImported);
      }

  • File.delete() not working properly

    Hi Forum!!
    I am trying with the below code :
    File file = new file("path");
    try{
    if(file.exists())
    System.+gc+();
    file.delete();
    System.+out+.println("Control in delete trx file after deletion"+ file.exists());
    }catch(SecurityException se){
    String msg= "Delete trx file if 3gttz file created : IO Problems";
    Log.+error+(msg, se);
    }file.exists() returns false But I when I check file, it still exhists with content 0 bytes .
    Is there a way to remove the entire file from the directory rather than deleting only the
    contents ? Need not to tell I did my initial search to solve the problem.
    Thanks
    Edited by: jagabandhu on Feb 10, 2009 1:09 PM

    georgemc wrote:
    PhHein wrote:
    corlettk wrote:
    We can't all be rocket surgeons, either ;-)Heart scientist is the word you're looking for.Or rockin' sturgeons. A (marginally) cooler - albeit fictional - alternative to this abominationFrom a crazy drunk:
    A "bottle in front of me" is better than a "frontal lobotomy"!
    (Sound out those two quoted strings.)

  • Okay, i have 2 bugs with maverick.  First, when I delete a file within a window, the files deletes but the preview doesn't delete until I close the window and reopen it.  Second, I work on a network of computers and the search feature is now buggy...

    Okay, i have 2 bugs with maverick.  First, when I delete a file within a window, the files deletes but the preview doesn't delete until I close the window and reopen it.  Second, I work on a network of computers and the search feature is now buggy...  When I search for a file, A) it asks me if it's a name, or it wont produce anything, and B), its slower than in prior OS versions and in some instances I have to toggle to a different directory and go back to my original directory in the search: menu bar or the search wont produce anything...  Very buggy. 

    It appears to me that network file access is buggy in Maverick.
    In my case I have a USB Drive attached to airport extreme (new model) and when I open folders on that drive they all appear empty. If I right click and I select get info after a few minutes! I get a list of the content.
    It makes impossible navigate a directory tree.
    File access has been trashed in Maverick.
    They have improved (read broken) Finder. I need to manage a way to downgrade to Lion again.

Maybe you are looking for

  • MacBook (13inch-late 2009) Heat/fan problem?? (2.26Ghz, white unibody)

    Hello guys, I have, maybe a problem with a unibody MacBook 2.26Ghz. Many times i have noticed that it is quite silently with his fan, even if some process are taking lot of CPU. For example, my MacBook Pro 13inch mid 2009 is not so silent, cause the

  • Pages/Numbers export pdf to (iBook)

    Since my iPad is basicly my new computer I got Pages and Numbers for it. Now everything works fine somfar, but I am missing one small thing. I did not buy 3G model, just Info on that part. When I work with different docs, I love to save them as .pdf,

  • DBMS_XPLAN.DISPLAY - predicate information

    As mentioned in Oracle® Database PL/SQL Packages and Types Reference oracle predicate information is only displayed when applicable. Do you konow when it is not applicable . First System Which shows predicate information SQL> create table ttt (a numb

  • DELIVERY TO PROFORMA INVOICE

    Dear All, Please help me getting this issue resolved. I am creating a delivery and some pupose i need to create a proforma invoice against the same. But system is allowing me to create multiple proforma invoices against a delivery. Delivery type i am

  • 999 Not generated

    Hi All, Im using biztalk server 2013. I need to generate 999 acknowledgment. in Parties itself we have one option to enable 999. After enabling, i created send port with filter condition BTS.MessageType==http://schemas.microsoft.com/Edi/x12#x12_999_r