File.exists returns false

File.exists returns false if the File object represents a symlink that is pointing to a non existing file.
How can I make it return true? I am using File.exists in a condition to
check if a symlink exists before calling File.delete.
I am using JDK 1.1.8.
Any help is appreciated.
Anil

Interesting. But it doesn't hurt to call delete() even the File doesn't exist, does it? Could you clarify why you need to confirm that before calling delete()?
PC

Similar Messages

  • File.exists() returns false even when the file exists

    hi,
    the exists() function of java.io.File function returns false even when the file exists on the file system. why is this? i checked the path of the file which gives me the correct path, but exists returns false. can anyone help?

    post some of the code you�re using - then maybe I can help you out
    //Anders

  • File.exists() returns false for existing file, help :)

    Hi all,
    I'm having the STRANGEST behavior... I'm working on a simple DNS management system, and before I overwrite a zone file, I want to check if it exists... but exists() is returning false even when the file exists.
    Here is my code snippet:
    finest( "Checking the existance of "+filename ) ;
    File zoneFile = new File( filename ) ;
    if ( zoneFile.exists() ) {
        finest( "Zone File "+zoneFile+" already exists." ) ;
        throw( new ZoneFileExistsException( fqdn ) ) ;
    else {
        finest( "Creating Zone File "+zoneFile ) ;
        ...It's producing this in the log (I cut off the timestamp parts):
    Checking the existance of /opt/DNS/db.testingbutler222.com
    Creating Zone File /opt/DNS/db.testingbutler222.com
    but...
    # ls -l /opt/DNS/db.testingbutler222.com
    -rw-r--r-- 1 root other 733 Aug 27 19:23 /opt/DNS/db.testingbutler222.com
    So... as you can see, the file CLEARLY exists... what the heck am I doing wrong or misunderstanding? This can't really be a bug in File, can it?
    Kenny Smith

    Hi,
    Thanks for your response, but as I showed in my first post, I'm using absolute paths. My log file contains this:
    Checking the existance of /opt/DNS/db.testbutler222.com...
    Existance of /opt/DNS/db.testbutler222.com=false
    # ls -l /opt/DNS/db.testbutler222.com
    -rw-r--r-- 1 root other 695 Aug 29 12:17 /opt/DNS/db.testbutler222.com
    I don't understand what is happening... I wrote a separate class that just tests the existance of a file, and that one is reporting the existance correctly.... (the source code is found in the second post above) I don't understand why my servlet code can see the file.
    I have jakarta-tomcat running as root, and the file I'm checking was created by the same servlet. I've double checked permissions and such, just to make sure it wasn't that.. but it's still not working.
    I even added code to create a FileReader from the file, that way if it throws a FileNotFoundException, I would know the file doesn't exist... and even though the file does exist, it throws the exception. :(
    Kenny

  • File.exists() returning false eventhough in reality the file exists

    Hi,
    I am trying to create a PDF file using FDFMerge software.
    For creating the PDF file, I need to execute a shell script from command-line, which I am doing using "Runtime.exec".
    ( I opted for this 'RunTime.exec' approach so as to read the output generated by the shell script.)
    After executing the shell script and reading all the output generated by the process, I am trying to check if the PDF file exists in the location the process created.
    When I do File.exists() its returning me "false" eventhough in reality the file exists.
    Any guess, why this is happening?
    Thanks in advance.
    -Sudheer

    Hi,
    I am trying to create a PDF file using FDFMerge
    software.
    For creating the PDF file, I need to execute a shell
    script from command-line, which I am doing using
    "Runtime.exec".
    ( I opted for this 'RunTime.exec' approach so as to
    read the output generated by the shell script.)
    After executing the shell script and reading all the
    output generated by the process, I am trying to check
    if the PDF file exists in the location the process
    created.
    When I do File.exists() its returning me "false"
    eventhough in reality the file exists.
    Any guess, why this is happening?
    Thanks in advance.
    -SudheerI know the following method works for checking if a file exists...
    public LineCounterB1()
              super( "GUI File reader" );
              tField = new JTextField("c:..\\FileScanner\\source\\test\\LineCounterB1.java");
              tField.setBackground(backColor1);
              tField.setForeground(foreColor1);
              tField.addActionListener( this );
    public void actionPerformed( ActionEvent ae )
              File name = new File( ae.getActionCommand() );
              if( name.exists() )
                   oArea.setText("FOUND " + name.getName() + "\n" +
                        (name.isFile() ? "File\n" : "Not a File\n" ) +
                        (name.isDirectory() ? "Directory\n" : "Not a Directory\n" ) +
                        (name.isAbsolute() ? "Absolute path\n" : "Not Absolute path\n" ) +
                        "Last modified" + name.lastModified() );
                   if( name.isFile() )
                        try
                             BufferedReader reader = new BufferedReader( new FileReader( name ) );
                             StringBuffer buffer = new StringBuffer();
                             String text = null;
                             oArea.append("\n\n");
                             while((text = reader.readLine())!=null)
                                  buffer.append(text + lineSep);
                             oArea.append(buffer.toString());
                        catch( IOException ioE)
                             JOptionPane.showMessageDialog(null,"Oooooo...");
                        //S7 scanner7 = new S7(/**name**/);                                        
                   else if( name.isDirectory())
                        String directory[] = name.list();
                        oArea.append("\n\nDir contents:\n");                    
                             for( int i=0; i<directory.length; i++)
                                  oArea.append( directory[i] + "\n");
              else
                   JOptionPane.showMessageDialog(null, "No such file or directory.");
         }

  • Check if file exists returns false. File is in system32

    I'm having a problem detecting if a file exists which was simply copied to the system32 directory.  I tried moving the file to various other directories and simply using a vi with the "Check if file or folder exists" action.  I've narrowed it down to not being able to find the file if I copy it to either c:\windows or c:\windows\system32. 
    I thought this could be a permissions issue, but did my best to assign the user name full control of the folders.
    Another interesting thing is if I make the file input a control and click on the "folder" icon to open a list of files, I cannot see the newly copied files in system32 directory either.  Very strange.
    This is on a Dell PC, Windows 7 professional/Labview 2010 SP1 (note I am running the vi. as an executable on this machine).  Could it be some setting in my project build?
    Solved!
    Go to Solution.

    If you're using Windows 7 64-bit, it may be related to the problems the user was having here:
    http://forums.ni.com/t5/LabVIEW/Problem-Using-quot-msg-quot-command-with-quot-System-Exec-vi/m-p/153...
    It may be that the LabVIEW functions are 32-bit and are getting redirected.

  • File Doesnt Exist / Returns false

    Hi Folks,
    I was just mucking around with some file IO and I used the following code to try verify a files existence before trying to open it:
    File Temp1 = new File(fullyQualifiedFileName);
         System.out.println(Temp1.getAbsolutePath());
         doesExist = Temp1.exists();
              System.out.println(fullyQualifiedFileName);
              System.out.println("Does "+ fullyQualifiedFileName +" Exist? -"+doesExist);
    The path prints correctly, the file does exist at the location give, the filename is correct but for some reason it returns false. Any ideas?
    Dave

    Does the user have access rights to the file?

  • File exists always false

    I'm making a mobile app for iOS and I have files in both the applicationDirectory (inside the app) and the cacheDirectory.
    No matter what I do a check on file.exists always returns false even though it is there - it's a video and it can play so it's there alright.
    What is going on?
    I have a string representing the path eg. "/assets/video.mp4"
    var f:File = File.applicationDirectory.resolvePath(filePath);
    trace(f.exists) //false

    When I trace the nativePath of the file I am trying to find it shows "C:\Users\User\AppData\Roaming\Arakaron.debug\Local Store". This is the exact path I am following in Explorer. Now, instead of applicationStorageDirectory I can do documentsDirectory and it reads that the file is in fact there. With the applicationStorageDirectory it only registers that the file exists after I copy from the embedded db file. 

  • Reasons File.Delete returning false

    Hi,
    I always assumed that if file.delete did not delete a file, it would raise an exception - however, today I have found out otherwise.
    What are some of the reasons why File.delete would return false (without throwing an exception). I've haven't seen the results of a chmod (which I am waiting on, but I have been assured they are set correctly - besides, I can delete files on the server directory through an Explorer on my Client PC.
    Thanks,
    Red.

    Thanks,
    It actually turned about to be an Oracle based setting (in ora.init) which was causing the problem.
    Of your answers -
    1. I believe would return a permission exception.
    2. It would think would raise an acess exception
    3. Should return false
    4. Would likely raise an exception
    Although I could be wrong...
    Thanks again,
    Red

  • File.exists()  returs false even the file is present in the specified path

    Hi,
    When i try to run the following program which checks whether the file exists in the given path or not
    public class FileCheck {
    public static void main(String[] a){
    String str = a[0];
    File f = new File(str);
    if(f.exists())
    System.out.println("File Exists ");
              else
         System.out.println("File does not Exists ");
    So on solaris 10(korean) we have file named in korean language under "usr" directory. When i try to run the above program on solaris 10(Korean) using the default jre (1.5)with the parameter "/usr/file name in korean language" .The output of the program is "File Exists"
    And when i run the same class file using the jre (1.6) which is installed in our application which is an english version with the same parameter ""/usr/file name in korean language"
    The output of the program is "File does not exists".
    And this problem is only with the files which contain the name in korean language.
    So do we need to set any properties for the jre in our application to work for files which are named in korean language. Any help will be highly appreciated.
    Thanks,
    GPK
    Edited by: gpk_04 on Nov 11, 2008 1:46 PM
    Edited by: gpk_04 on Nov 11, 2008 1:57 PM

    My guess is that Java 5 and 6 are picking up the file system encoding differently. As a consequence, the JVM is either:
    1. reading and converting your command line argument incorrectly, or
    2. reading and converting the file name from the file system incorrectly.
    Write a quicky, short app that prints out the file encoding of your host. Run this under 5 and then 6. Do you see different outputs?

  • Record Collection Count = 1, but Exists is return false?

    Hi All,
    OracleDB: 10g
    I have a collection record I am using to store information in a sproc. Before I do any work with it I check if any data exists in the record (l_tab_cost_rec.EXISTS(1)).
    What is strange is l_tab_cost_rec.EXISTS(1) is returning false, but l_tab_cost_rec.Count is returning a count = 1?
    Why is Exists returning false, but the count is returning 1?
    Record Definition:
    TYPE type_cost_rec IS RECORD
    (item_id NUMBER
    ,item_cost NUMBER
    ,org_id NUMBER
    TYPE tab_cost_rec IS TABLE OF type_cost_rec INDEX BY BINARY_INTEGER;
    l_tab_cost_rec tab_cost_rec;

    Becaues exists(1) checks if an element exists that has index 1:
    SQL> declare
      2  type t is table of number index by binary_integer;
      3  v t;
      4  begin
      5   v(0):=0;
      6   dbms_output.put_line('count='||v.count);
      7   if v.exists(1) then
      8      dbms_output.put_line('1 exists!');
      9   else
    10      dbms_output.put_line('1 doesn''t exist!');
    11   end if;
    12   if v.exists(0) then
    13      dbms_output.put_line('0 exists!');
    14   else
    15      dbms_output.put_line('0 doesn''t exist!');
    16   end if;
    17  end;
    18  /
    count=1
    1 doesn't exist!
    0 exists!
    PL/SQL procedure successfully completed.Max
    http://oracleitalia.wordpress.com

  • Java.io.File exists() problem

    I have a web application deployed on a Windows 2000 server and am running Tomcat 4. I want to check for the existence of an image file before displaying it and am trying to use the java.io.File.exists() method. I am using the following code:
    String strPicUrl = "/images/thefile.jpg"; //Actual value comes from database
    File theFile = new File(application.getRealPath(strPicUrl));
    out.print("File Exists: " + theFile.exists() + "<br>");the actual file name in this example is "/images/theFile.jpg", and theFile.exists() always returns true if the file is there, but differs in case. If I try to display the image it doesnt show up under Tomcat because aliasing is turned off by default. I need to find a way to determine if a file exists based on actual case matching. This way if I get a "true" value, the file should be accessible and/or viewable via the JSP engine.
    Any ideas how to perform a case sensitive "exists()" regardless of the underlying OS file system?

    This looks awesome, but when I tried to implement it without creating a class, I get a method error. Here is the code below:
    String theDir = "C:\\Dir\\Subdir\\";
    FileFilter theFilter = new FileFilter() {
         private String _theFile = null;
         public boolean accept(File file)
              if (file.isDirectory()) return false;
              String fileName = file.getName();
              if (fileName.endsWith(_theFile)) return true;
              return false;
         public void setTheFile(String theFileParam)  
              _theFile = theFileParam;  
    theFilter.setTheFile("theFile.jpg");When I run this I get the following error:
    [javac] ...blah error stuff...
    [javac] cannot resolve symbol
    [javac] symbol : method setTheFile (java.lang.String)
    [javac] location: interface java.io.FileFilter
    [javac] theFilter.setTheFile("theFile.jpg");
    Since I am invoking the FileFilter object directly and not instantiating it in a class, is that causing the error or am I declaring "setTheFile()" wrong?

  • File.exists() is not accurate on smb2 network share (use WatchService?)

    Hi,
    According to this document: SMB2 Client Redirector Caches Explained File.exists() is not accurate on a smb2 network share. I am not able to change any register settings, so I want to deal with it. According to the document there is an API to get the notifications from the file system. I assumed that the WatchService is the Java implementation of this API. Am I correct?
    I started with the WatchDir example from the jdk samples and stripped it a bit. I only need to know when a file is created and delete (I don't care about file modifications). For testing I have added new File.exists() when a new event has been triggered. I also start a separated Thread which test the file existence also. When I don't start this separated thread the file exists returns true immediately. When the extra thread is started it is not accurate any more. I need a more accurate file.exists check in the whole application and all running threads.
    The output for my test case is this:
    FileExistsThread: subdir\test.txt == false
    watch registered for dir: subdir\
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    WatchDir event: ENTRY_CREATE: test.txt
    WatchDir: subdir\test.txt exists == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == false
    FileExistsThread: subdir\test.txt == true
    FileExistsThread: subdir\test.txt == true
    FileExistsThread: subdir\test.txt == true
    FileExistsThread: subdir\test.txt == true
    As you can see the file test.txt  is created on line 9. The FileExistsThread have seen it on line 20, (at least 10 x 300 ms later).
    For testing I have used 2 Windows 7 pc's (with smb2 enabled which is default). The working directory must be on the remote pc and the file test.txt must be created (or copied from another folder) on the remote pc (not using the network drive, but on the pc itself).
    Here is my test code:
    package nl.test.main;
    import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
    import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
    import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.ClosedWatchServiceException;
    import java.nio.file.FileSystems;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.WatchEvent;
    import java.nio.file.WatchKey;
    import java.nio.file.WatchService;
    public class WatchDir
      private final WatchService _watcher;
      private final String _dir;
      public WatchDir( String dir ) throws IOException
        _dir = dir;
        _watcher = FileSystems.getDefault().newWatchService();
        Paths.get( dir ).register( _watcher, ENTRY_CREATE, ENTRY_DELETE );
        System.out.println( "watch registered for dir: " + dir );
      public void run()
        try
          while ( true )
            WatchKey key = _watcher.take();
            for ( WatchEvent<?> event : key.pollEvents() )
              WatchEvent.Kind<?> kind = event.kind();
              if ( kind == OVERFLOW )
                continue;
              @SuppressWarnings( "unchecked" )
              WatchEvent<Path> ev = (WatchEvent<Path>)event;
              Path fileName = ev.context();
              System.out.println( "WatchDir event: " + kind.name() + ": " + fileName );
              if ( kind == ENTRY_CREATE )
                String realPath = _dir + fileName;
                System.out.println( "WatchDir: " + realPath + " exists == " + new File( realPath ).exists() );
            key.reset();
        catch ( ClosedWatchServiceException x )
          return;
        catch ( InterruptedException ex )
          return;
      public static void main( String[] args )
        Thread t = new Thread( new Runnable()
          @Override
          public void run()
            try
              while ( true )
                String filename = "subdir\\test.txt";
                boolean fileExists = new File( filename ).exists();
                System.err.println( "FileExistsThread: " + filename + " == " + fileExists );
                Thread.sleep( 300 );
            catch ( InterruptedException e )
              e.printStackTrace();
              return;
        t.start();
        try
          new WatchDir( "subdir\\" ).run();
        catch ( IOException e )
          e.printStackTrace();
    Any idea's?
    Thanks,
    Olaf

    If you donot have access to note 45172.1 as specified by Laurent Schneider.
    Snippet from note
    a. Mapped Drive : To use a mapped drive, the user that the service starts as
    must have setup a drive to match UTL_FILE_DIR and be logged onto the server
    when UTL_FILE is in use.
    b. Universal Naming Convention : UNC is preferable to Mapped Drives because
    it does not require anyone to be logged on and UTL_FILE_DIR should be set to
    a name in the form :
    \\\<machine name>\<share name>\<path>
    or
    "\\<machine name>\<share name>\<path>"

  • In a javascript function invoked from an onsubmit handler, if the function returns false, the form is still submitted. If I find an error in a form, how do I cancel the submit?

    HTML form has: action="/TTFFRP/addlicense.rex" method="get" onsubmit="validate_data();"
    validate_data is defined in tags:
    function validate_data()
    alert('in validate routine');
    if (document.getElementById('custname').value == '')
    alert('Customer name must not be blank; put in name of organization licensing File RePackager');
    return false;
    }

    Try posting at the Web Development / Standards Evangelism forum at MozillaZine. The helpers over there are more knowledgeable about web page development issues with Firefox.
    [http://forums.mozillazine.org/viewforum.php?f=25]
    You'll need to register and login to be able to post in that forum.

  • File Exists Always returning false

    I am using the File.applicationStorageDirectory.resolvePath("myData.db") to reference the location of my SQLite DB file. When I browse to the folder in question I can see that the file is in fact there, however and traces I implement of dbfile.exists is false. It only ever returns true should I use my defaultdb and CopyTo the file of the myData.
    What seems to be the issue here?

    When I trace the nativePath of the file I am trying to find it shows "C:\Users\User\AppData\Roaming\Arakaron.debug\Local Store". This is the exact path I am following in Explorer. Now, instead of applicationStorageDirectory I can do documentsDirectory and it reads that the file is in fact there. With the applicationStorageDirectory it only registers that the file exists after I copy from the embedded db file. 

  • File.exists() takes too long to return.

    Hi.
    I have written a program which checks to see if a particular shared file is present on a number of different computers. The path to the file is the same on all the computers.
    I construct the File with IP + path.
    Then I call file.exists()
    If the remote computer is on and the file is present, then 'true' is returned quite quickly. But if the file is not available then 'false' is returned but only after about 30 seconds. This is too long and I want to set some sort of time out for the method after about 3 seconds. So that if the file is not found before the timeOut time, 'false' will be returned.
    Is there any way I can do this???
    Thanks,
    Jim

    Hi,
    I am already using Threads, here is my code:
    public class FileExistsThread extends Thread {
         private File file;
         private long tryTime;
         private boolean exists;
         private boolean changed;
         public FileExistsThread(File file, long tryTime) {
              this.file = file;
              this.tryTime = tryTime;
         public void run() {
              new Thread() {
                   public void run() {
                        try {
                             Thread.sleep(tryTime);
                        } catch(Exception e) {}
                        exists = false;
                        changed = true;
              }.start();
              exists = file.exists();
              changed = true;
         public boolean fileExists() {
              start();
              while(!changed);
              return exists;
    }The Problem is that I cant close my program while a file.exists() method is still executing no matter what Thread it is in. Say I'm looking for a file which the program will take 30 seconds to establish is not available. Then for that 30 seconds my program will refuse to close. Sometimes it can be much longer than this.
    This is why I still need some sort of timeout mechanism.
    Any Ideas?
    Cheers,
    Jim

Maybe you are looking for

  • Save As - Settings and Filename Incrementer

    Hello All, I'm on CS5/CS6, i use a panel which i created in configurator. I have it run actions, menu items etc. All works great. Problem: I'm sick and tired of saving each open active image as JPG and incrementing the filename by 1.  I'm hoping some

  • SSD in MBP 13" Retina Late 2013 doesn't work - Can't boot at all

    I have a new MacBook Pro 13" Retina which works flawlessly. It has a factory installed 512 GB SSD, which also works flawlessly. Then I bought basically the same type of 512 GB SSD, 2nd hand but new, which I intended to install in another MacBook Pro

  • Ipod mini/updater

    I have just tried to set my ipod to its original factory settings but it is saying cannot mount ipod. What does this mean? PLEASE HELP!!! I have gone without my ipod for way too long. Thanks.

  • How to update cost condition VPRS and Updating from VPRS to new cond ZVPR

    Hi All, How to do and is there any way to update the VPRS cost condition whenever vendor sends confirmation of material and cost after purchase order. After receiving the confirmation form the vendor,the VPRS cost condition should get updated in the

  • User preferences oracle package name

    Hello Can anyone tell me in which package the user preferences are stored in oracle portal. i am using 10.1.4 Thanks Paul