简体   繁体   中英

How to get to a file by passing relative path in java?

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 (ie 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")

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM