简体   繁体   中英

Access file without knowing absolute path, only knowing file name

I'm trying to use a file in my code but I don't want to have specify the absolute file path, only the file name, for example "fileName.txt".

I want to do this so I have the ability to use this code on different laptops where the file may be stored in different folders.

The code below is what I'm using at the moment but I receive a NoSuchFileException when I ran it.

FileSystem fs FileSystems.getDefault();
Path fileIn = Paths.get("fileName.txt");

Any ideas how to overcome this problem so I can find the file without knowing its absolute path?

Ideas on how to find the file without knowing its absolute path:

  1. Instruct the user of the app to place the file in the working directory.

  2. Instruct the user of the app to give the path to the file as a program argument, then change the program to use the argument.

  3. Have the program read a configuration file, found using options 1 or 2, then instruct the user of the app to give the path to the file in the configuration file.

  4. Prompt the user for the file name.

  5. (Not recommended) Scan the entire file system for the file, making sure there is only one file with the given name. Optional: If more than one file is found, prompt the user for which file to use.

if you don't ask the user for the complete path, and you don't have a specific folder that it must be in, then your only choice is to search for it.

Start with a rootmost path. Learn to use the File class. Then search all the children. This implementation only returned the first file found with that name.

public File findFile(File folder, String fileName) {
    File fullPath = new File(folder,fileName);
    if (fullPath.exists()) {
        return fullPath;
    }
    for (File child : folder.listFiles()) {
        if (child.isDirectory()) {
            File possible = findFile(child,fileName);
            if (possible!=null) {
                return possible;
            }
        }
    }
    return null;
}

Then start this by calling either the root of the file system, or the configured rootmost path that you want to search

File userFile = findFile(  new File("/"), fileName );

the best option, however, is to make the user input the entire path. There are nice file system browsing tools for most environments that will do this for the user.

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