1

I am trying to understand "How to get to file by passing relative path of a file or folder?" . Here is the example:

CODE:

  public class somex {
    public static void main {
       String fileName = System.getProperty("user.dir");   <---This gives me path for the current working directory.
       File file = new File(fileName + "../../xml_tutorial/sample.xlsx" );
       System.out.println(file.getCanonicalPath());         <---This gives me path for the file that is residing in folder called "xml_tutorial".
     }
  }

    >>>> 

Here, I know the file location so i was able to pass correct relative path. And, managed to print the file path. I have deleted the "sample.xlsx" and executed the above code; With no failing it gives me the path name and it is same path as when the file exists (i.e. before deleting). How it is possible ? I am expecting EXCEPTION here. why it is not throwing exception ?

Two, I want to use regular expression for the file name, such as: "../../xml_tutorial/samp.*". But this doesn't do the job and it gives me IOException. Why it is not able to identify the file sample.xlsx ? (NOTE: this is when the file exist and one hundred precent sure there is only one file with the name "sample.xlsx")

MKod
  • 803
  • 5
  • 20
  • 33
  • 1. you can check the file with file.exists() method. 2. java not support wildcard, you can find answer here http://stackoverflow.com/questions/794381/how-to-find-files-that-match-a-wildcard-string-in-java – Terry Ma May 04 '13 at 14:05
  • 1
    Please ask **one** question per question. – T.J. Crowder May 04 '13 at 14:07

1 Answers1

3

I have deleted the "sample.xlsx" and executed the above code; With no failing it gives me the path name and it is same path as when the file exists (i.e. before deleting). How it is possible ? I am expecting EXCEPTION here. why it is not throwing exception ?

File doesn't care whether the file actually exists. It just resolves the path. There's no need for the file to exist in order to take the path

/home/tjc/a/b/c/../../file.txt

...and turn it into the canonical form

/home/tjc/a/file.txt

If you want to know whether the file on that path actually exists, you can use the exists() method.


On your second, unrelated question:

Two, I want to use regular expression for the file name, such as: "../../xml_tutorial/samp.*". But this doesn't do the job and it gives me IOException. Why it is not able to identify the file sample.xlsx ?

There's nothing in the File documentation saying that it supports wildcards. If you want to do searches, you'll want to use list(FilenameFilter) or listFiles(FilenameFilter) and a FilenameFilter implementation, or listFiles(FileFilter) and a FileFilter implementation.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875