简体   繁体   中英

How to access an existing directory in your project without knowing it's path Java

I want to write a method that iterates through current files in a directory named "Users". Since different machines have different absolute paths i need a way of accessing this folder without hardcoding the path.

assume I am in the src folder and the Users folder already exists.


    public static boolean validUsername(String user) {
        File dir = new File("./Users/");
        File[] directoryListing = dir.listFiles();
        System.out.println(dir);
        System.out.println(directoryListing);
        if (directoryListing != null) {
            for (File child : directoryListing) {
                // Do something with child
                // think child is filename?
                if (user.equals(child.getName())){
                    return false;

                }
            }
        }
        return true;
    }

whenever i call this method in the main method, the directory listing variable is always null, even if the Users folder has files in it already.

There are many ways to solve this. There is some of them

  1. Put your path in config file
  2. Use relative path
  3. Use System property variables

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